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
find-the-difference-of-two-arrays
python_o[n]_hashtable
python_on_hashtable-by-adhamehabelsheikh-9w3l
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
AdhamEhabElsheikh
NORMAL
2023-11-16T08:22:56.067913+00:00
2023-11-16T08:22:56.067941+00:00
896
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(object):\n def findDifference(self, nums1, nums2):\n hashtable = {}\n first_true_second_false = []\n second_true_first_false = []\n for num in nums1:\n if num not in hashtable:\n hashtable[num] = [True,False]\n for num in nums2:\n if num in hashtable:\n hashtable[num][1] = True\n else:\n hashtable[num] = [False,True]\n for key, value in hashtable.items():\n if value[0] and not value[1]:\n first_true_second_false.append(key)\n elif not value[0] and value[1]:\n second_true_first_false.append(key)\n return [first_true_second_false,second_true_first_false]\n \n \n """\n :type nums1: List[int]\n :type nums2: List[int]\n :rtype: List[List[int]]\n """\n \n```
5
0
['Python']
2
find-the-difference-of-two-arrays
88.6% beatable ✨ || Easy JS Sol. || Understandable (Sets) Approach 💯🧑‍💻
886-beatable-easy-js-sol-understandable-1g77k
Intuition\n Describe your first thoughts on how to solve this problem. \n\n- The below code implements a function called findDifference that takes in two arrays
Rajat310
NORMAL
2023-05-03T23:44:36.895299+00:00
2023-05-04T21:02:05.925594+00:00
241
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n- The below code implements a function called **findDifference** that takes in two arrays, nums1 and nums2, and returns an array containing **two arrays**. The **two arrays** inside the returned array are the disjoint elements of **nums1** and **nums2**.\n\n\n\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n1. To accomplish the result, the code creates ***two sets***, **set1** and **set2**, to store the ***unique elements*** of **nums1** and **nums2**, respectively.\n2. It then creates two ***empty arrays***, **result1** and **result2**, to store the disjoint elements of **nums1** and **nums2**, respectively.\n3. Next, the code iterates over the union of the two sets using the ***spread operator ([...set1, ...set2])***. \n4. For each element, it checks if the element is in **set2** and if so, pushes it into **result1**. \n5. Similarly, if the element is in **set1**, it is pushed into **result2**.\n6. Finally, the code **returns** an array containing **result1** and **result2**.\n\n##### - Overall, the approach of the above code is to use ***sets*** to efficiently find the unique elements in the two input arrays and then compare them to find the disjoint elements.\n\n\n\n\n\n\n\n\n\n\n\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n1. Here n is the length of the longer of the two input arrays (nums1 and nums2). \n2. This is because the code iterates over the union of the two sets, which takes at most n iterations since each element is only visited once. \n3. Set operations (such as has) have an average time complexity of **O(1)**, so they don\'t add any additional complexity to the algorithm.\n\n\n\n\n\n\n\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n1. Since the two sets and two arrays created have a maximum size of **n** ***(the size of the longer of the two input arrays)***.\n\n\n\n\n\n\n\n\n\n\n# Code\n```\n/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @return {number[][]}\n */\nvar findDifference = function(nums1, nums2) {\n \n // Create two empty Sets to store unique elements of nums1 and nums2\n \n let set1 = new Set(nums1);\n \n let set2 = new Set(nums2);\n \n // Create two arrays to store the disjoint elements\n \n let result1 = [];\n \n let result2 = [];\n \n // Iterate over nums1 and nums2 together and add the disjoint elements to the result arrays\n \n for (let num of [...set1, ...set2]) {\n \n if (!set2.has(num)) {\n \n result1.push(num);\n }\n \n if (!set1.has(num)) {\n \n result2.push(num);\n }\n }\n \n // Return the disjoint elements in an array\n \n return [result1, result2]; \n};\n```\n![cat img for upvote on LC.jpeg](https://assets.leetcode.com/users/images/f1df6dd1-c032-4294-b13e-a59cfc7f9541_1683234123.083215.jpeg)\n\n
5
0
['Array', 'Hash Table', 'JavaScript']
0
find-the-difference-of-two-arrays
C solution
c-solution-by-hoouhoou-cncv
\nint** findDifference(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize, int** returnColumnSizes){\n returnColumnSizes[0] = calloc(2, si
HoouHoou
NORMAL
2023-05-03T13:23:18.824000+00:00
2023-05-03T13:28:21.340092+00:00
1,004
false
```\nint** findDifference(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize, int** returnColumnSizes){\n returnColumnSizes[0] = calloc(2, sizeof(int));\n *returnSize = 2;\n \n int **ret = malloc(sizeof(int*) * 2);\n ret[0] = malloc(sizeof(int) * 1000);\n ret[1] = malloc(sizeof(int) * 1000);\n int *table = calloc(2001,sizeof(int));\n \n for (int i = 0; i < nums2Size; i++)\n table[nums2[i] + 1000]++;\n \n for (int i = 0; i < nums1Size; i++){\n if (table[nums1[i] + 1000] == 0)\n ret[0][returnColumnSizes[0][0]++] = nums1[i];\n table[nums1[i] + 1000] = -1;\n }\n \n for (int i = 0; i < 2001; i++)\n if (table[i] > 0)\n ret[1][returnColumnSizes[0][1]++] = i - 1000;\n \n free(table);\n return ret;\n}\n```
5
0
['C']
0
find-the-difference-of-two-arrays
JavaScript one liner using just filter.
javascript-one-liner-using-just-filter-b-yjh9
\n\n/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @return {number[][]}\n */\nvar findDifference = function(nums1, nums2) {\n return([nums1.
user9212eH
NORMAL
2023-05-03T10:51:16.707288+00:00
2023-05-03T10:51:16.707321+00:00
1,087
false
\n```\n/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @return {number[][]}\n */\nvar findDifference = function(nums1, nums2) {\n return([nums1.filter((e,i)=> nums1.indexOf(e) === i && !nums2.includes(e)),nums2.filter((e,i)=> nums2.indexOf(e) === i && !nums1.includes(e))]);\n};\n```
5
0
['JavaScript']
1
find-the-difference-of-two-arrays
Easy java solution || Begginer friendly
easy-java-solution-begginer-friendly-by-03wd6
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
antovincent
NORMAL
2023-05-03T07:15:12.331484+00:00
2023-05-03T07:15:12.331512+00:00
1,859
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 static List<Integer> f(int [] c ,int [] d){\n List<Integer> r = new ArrayList<Integer>();\n for(int i=0;i<c.length;i++){\n boolean f=false;\n for(int j=0;j<d.length;j++){\n if(c[i]==d[j]){\n f=true;\n break;\n }\n }\n if(!f&&!r.contains(c[i])){\n r.add(c[i]);\n }\n }\n return r;\n }\n public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {\n List<List<Integer>> a = new ArrayList<List<Integer>>();\n \n boolean f=true;\n a.add(f(nums1,nums2));\n a.add(f(nums2,nums1));\n return a;\n \n }\n}\n```
5
0
['Java']
2
find-the-difference-of-two-arrays
Java Solution for Find the Difference of Two Arrays Problem
java-solution-for-find-the-difference-of-kxia
Intuition\n Describe your first thoughts on how to solve this problem. \nThe intuition behind the solution is to use two sets to store the distinct elements of
Aman_Raj_Sinha
NORMAL
2023-05-03T03:04:34.300768+00:00
2023-05-03T03:04:34.300800+00:00
763
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind the solution is to use two sets to store the distinct elements of the two input arrays nums1 and nums2, respectively. Then, the difference between the two sets can be computed to find the elements that are present in one set but not the other. Finally, these elements are added to separate lists, which are returned as the result.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe given solution is for the problem of querying the sum of elements in a rectangular region of a matrix. The intuition behind the solution is to precompute the prefix sum matrix, where the value at each cell represents the sum of all elements in the submatrix from (0,0) to that cell. Then for each query, the sum of the required region can be calculated using the precomputed values in constant time.\n\nThe approach used is to compute the prefix sum matrix in the constructor of the `NumMatrix` class. For this, two nested loops are used to iterate over all cells of the matrix. At each cell, the sum of the current row and all previous rows up to the current row, and the sum of the current column and all previous columns up to the current column, is calculated using the precomputed value from the previous row or column. Finally, the sum of the current cell is calculated by subtracting the value of the top-left submatrix, which was added twice.\n\nFor each query of a rectangular region, the sum of the submatrix is calculated using the precomputed values of the prefix sum matrix. Depending on the location of the top-left and bottom-right corners of the submatrix, different cases are handled to calculate the final result using the precomputed values.\n\n\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of the constructor is O(mn), where m and n are the dimensions of the matrix, as it requires iterating over all cells of the matrix. The time complexity of each query is O(1), as it only requires calculating the sum of four cells using the precomputed values.\n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity of the solution is O(mn), as the prefix sum matrix requires the same amount of space as the original matrix.\n\n# Code\n```\nclass Solution {\n public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {\n Set<Integer> set1 = new HashSet<>();\n Set<Integer> set2 = new HashSet<>();\n for (int num : nums1) \n {\n set1.add(num);\n }\n for (int num : nums2) \n {\n set2.add(num);\n }\n List<Integer> diff1 = new ArrayList<>();\n List<Integer> diff2 = new ArrayList<>();\n for (int num : set1) \n {\n if (!set2.contains(num)) \n {\n diff1.add(num);\n }\n }\n for (int num : set2) \n {\n if (!set1.contains(num)) \n {\n diff2.add(num);\n }\n }\n List<List<Integer>> answer = new ArrayList<>();\n answer.add(diff1);\n answer.add(diff2);\n return answer;\n }\n}\n```
5
0
['Java']
0
find-the-difference-of-two-arrays
🗓️ Daily LeetCoding Challenge May, Day 3
daily-leetcoding-challenge-may-day-3-by-swpw4
This problem is the Daily LeetCoding Challenge for May, Day 3. Feel free to share anything related to this problem here! You can ask questions, discuss what you
leetcode
OFFICIAL
2023-05-03T00:00:28.373224+00:00
2023-05-03T00:00:28.373305+00:00
6,147
false
This problem is the Daily LeetCoding Challenge for May, Day 3. Feel free to share anything related to this problem here! You can ask questions, discuss what you've learned from this problem, or show off how many days of streak you've made! --- If you'd like to share a detailed solution to the problem, please create a new post in the discuss section and provide - **Detailed Explanations**: Describe the algorithm you used to solve this problem. Include any insights you used to solve this problem. - **Images** that help explain the algorithm. - **Language and Code** you used to pass the problem. - **Time and Space complexity analysis**. --- **📌 Do you want to learn the problem thoroughly?** Read [**⭐ LeetCode Official Solution⭐**](https://leetcode.com/problems/find-the-difference-of-two-arrays/solution) to learn the 3 approaches to the problem with detailed explanations to the algorithms, codes, and complexity analysis. <details> <summary> Spoiler Alert! We'll explain these 2 approaches in the official solution</summary> **Approach 1:** Brute Force **Approach 2:** HashSet </details> If you're new to Daily LeetCoding Challenge, [**check out this post**](https://leetcode.com/discuss/general-discussion/655704/)! --- <br> <p align="center"> <a href="https://leetcode.com/subscribe/?ref=ex_dc" target="_blank"> <img src="https://assets.leetcode.com/static_assets/marketing/daily_leetcoding_banner.png" width="560px" /> </a> </p> <br>
5
0
[]
34
find-the-difference-of-two-arrays
Superb Questions--->Python3
superb-questions-python3-by-ganjinaveen-i58b
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
GANJINAVEEN
NORMAL
2023-03-17T13:38:37.770765+00:00
2023-03-17T13:43:16.930666+00:00
1,525
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 findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:\n list1,list2,list3=[],[],[]\n for i in nums1:\n if i in nums2:\n continue\n else:\n list2.append(i)\n for j in nums2:\n if j in nums1:\n continue\n else:\n list3.append(j)\n list1.append(list(set(list2)))\n list1.append(list(set(list3)))\n return list1\n```\n```\nclass Solution:\n def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:\n m,n=set(nums1),set(nums2)\n return [list(m-n),list(n-m)]\n\n```
5
0
['Python3']
0
find-the-difference-of-two-arrays
Learner friendly Java Solution
learner-friendly-java-solution-by-himans-bhnh
\n\n# Code\njava []\nclass Solution {\n public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {\n Set<Integer> s1 = new HashSet<>();\n
HimanshuBhoir
NORMAL
2023-01-01T16:32:38.658648+00:00
2023-01-01T16:32:38.658687+00:00
926
false
\n\n# Code\n``` java []\nclass Solution {\n public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {\n Set<Integer> s1 = new HashSet<>();\n for(int i: nums1) s1.add(i);\n Set<Integer> s2 = new HashSet<>();\n for(int i: nums2) s2.add(i);\n Set<Integer> common = new HashSet<>();\n for(int i: s1){\n if(s2.contains(i)) common.add(i);\n }\n s1.removeAll(common);\n s2.removeAll(common);\n return Arrays.asList(new ArrayList<>(s1), new ArrayList<>(s2));\n }\n}\n```
5
0
['Java']
0
find-the-difference-of-two-arrays
perfectly clear code!! using c++
perfectly-clear-code-using-c-by-joshua__-izk1
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
Joshua__J
NORMAL
2023-01-01T13:11:09.991644+00:00
2023-01-01T13:11:09.991687+00:00
1,054
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n unordered_map<int,int>map1;\n unordered_map<int,int>map2;\n for(int i=0;i<nums1.size();i++){\n map1[nums1[i]]++;\n }\n for(int j=0;j<nums2.size();j++){\n map2[nums2[j]]++;\n }\n vector<vector<int>>ans;\n vector<int>v;\n for(int i=0;i<nums1.size();i++){\n if(map2[nums1[i]]==0){\n v.push_back(nums1[i]);\n map2[nums1[i]]=1;\n }\n }\n ans.push_back(v);\n vector<int>v2;\n for(int i=0;i<nums2.size();i++){\n if(map1[nums2[i]]==0){\n v2.push_back(nums2[i]);\n map1[nums2[i]]=1;\n }\n }\n ans.push_back(v2);\n return ans;\n }\n};\n```
5
0
['Array', 'Hash Table', 'C++']
0
find-the-difference-of-two-arrays
Solution using Sorting
solution-using-sorting-by-shailu00-1djb
\nbool ispresent(vector<int>& nums, int val)\n {\n for(int i=0;i<nums.size(); i++)\n {\n if(nums[i]==val) return true;\n }\n
Shailu00
NORMAL
2022-04-06T06:59:24.087496+00:00
2022-07-02T19:24:59.900328+00:00
629
false
```\nbool ispresent(vector<int>& nums, int val)\n {\n for(int i=0;i<nums.size(); i++)\n {\n if(nums[i]==val) return true;\n }\n return false;\n }\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n sort(nums1.begin() , nums1.end() );\n sort(nums2.begin() , nums2.end() );\n vector<int>v1,v2;vector<vector<int>> ans;\n for(int i=0;i<nums1.size();i++)\n {\n if(ispresent(nums2,nums1[i])==false) v1.push_back(nums1[i]);\n }\n for(int i=0;i<nums2.size();i++)\n {\n if(ispresent(nums1,nums2[i])==false) v2.push_back(nums2[i]);\n }\n v1.erase( unique( v1.begin(), v1.end() ), v1.end() );\n v2.erase( unique( v2.begin(), v2.end() ), v2.end() );\n ans.push_back(v1); ans.push_back(v2);\n return ans;\n }\n```
5
0
['C', 'Sorting']
1
find-the-difference-of-two-arrays
Quick and Easy C++ Solution Beats 89% 2 Sets approach
quick-and-easy-c-solution-beats-89-2-set-ohre
Intuition\n Describe your first thoughts on how to solve this problem. \n- eliminate duplicates\n- find unique values in nums1 and nums 2 simultaneously\n# Appr
gbw30
NORMAL
2024-12-01T07:19:40.035493+00:00
2024-12-01T07:19:40.035523+00:00
253
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- eliminate duplicates\n- find unique values in nums1 and nums 2 simultaneously\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. We initialize 2 sets and store the values of the arrays in them to eliminate the duplicates.\n2. We run a for loop through the set containing nums1 and check if nums2 has the value using the set. If it doesn\'t, its unique to 1, so we add it to a vector. If it exists in both, we remove it from set 2 so that at the end, set 2 will have unique values to 2.\n3. After the for loop, set 2 should contain the values unique to 2 so we put them in a vector.\n4. Finally, we push both vectors into the vector of vectors to return.\n# Complexity\n- Time complexity: \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n+m), where n is the size of nums1 and m is the size of nums2.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n+m), where n is the size of nums1 and m is the size of nums2.\n\n![image.png](https://assets.leetcode.com/users/images/ef78b336-5c38-467b-8e2d-3f96a5e7fee6_1733037571.3389804.png)\n\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n vector<vector<int>>res;\n vector<int>uniqueOne;\n unordered_set<int>n1(nums1.begin(), nums1.end());\n unordered_set<int>n2(nums2.begin(), nums2.end());\n for (auto x : n1){\n if (n2.count(x) == 0){uniqueOne.push_back(x);}\n else {n2.erase(x);}\n }\n res.push_back(uniqueOne);\n vector<int>uniqueTwo(n2.begin(), n2.end());\n res.push_back(uniqueTwo);\n return res;\n }\n};\n```
4
0
['C++']
1
find-the-difference-of-two-arrays
C++ and Python3 || Hashset || Simple and Optimal
c-and-python3-hashset-simple-and-optimal-rm3e
\n\n# Code\nPython3 []\nclass Solution:\n def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:\n set1 = set(nums1)\n
meurudesu
NORMAL
2024-02-25T08:17:40.224048+00:00
2024-02-25T08:17:40.224079+00:00
1,374
false
> ![image.png](https://assets.leetcode.com/users/images/221a6a8a-6b51-470b-9478-90f840cb4a8d_1708848962.8635645.png)\n\n# Code\n```Python3 []\nclass Solution:\n def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:\n set1 = set(nums1)\n set2 = set(nums2)\n ans = [[], []]\n for num in set1:\n if num not in set2:\n ans[0].append(num)\n for num in set2:\n if num not in set1:\n ans[1].append(num)\n return ans\n```\n```C++ []\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n unordered_set<int> set1(nums1.begin(), nums1.end());\n unordered_set<int> set2(nums2.begin(), nums2.end());\n vector<vector<int>> ans(2);\n for(auto num : set1) {\n if(set2.contains(num) == false) ans[0].push_back(num);\n }\n for(auto num : set2) {\n if(set1.contains(num) == false) ans[1].push_back(num);\n }\n return ans;\n }\n};\n```
4
0
['Array', 'Hash Table', 'C++', 'Python3']
1
find-the-difference-of-two-arrays
Merge 2 Sorted Array xx Two Pointer
merge-2-sorted-array-xx-two-pointer-by-a-qqby
Intuition\n Describe your first thoughts on how to solve this problem. \nI have been solving Union and Intersection problems by merging two sorted array using t
avykr07
NORMAL
2024-02-06T14:37:39.984850+00:00
2024-02-06T14:37:39.984881+00:00
1,489
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI have been solving Union and Intersection problems by merging two sorted array using two-pointer (LC349, LC350). To check for duplicates use the logic used in LC26, LC80.\n\n# Complexity\n- Time complexity: O(n log n + m log m)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nBecause sorting is involved.\n- Space complexity: O(n + m) \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {\n Arrays.sort(nums1);\n Arrays.sort(nums2);\n // ArrayList<ArrayList<Integer>> arr = new ArrayList<>();\n List<List<Integer>> arr = new ArrayList<>();\n for(int i = 0; i < 2; i++){\n arr.add(new ArrayList<Integer>());\n }\n int n = nums1.length; int m = nums2.length;\n int i = 0; int j = 0;\n int x = 0; int y = 0;\n while(i < n && j < m) {\n if(nums1[i] < nums2[j]){\n if(x < 1 || nums1[i] != arr.get(0).get(x-1)){\n arr.get(0).add(nums1[i]);\n x++;\n }\n i++;\n } else if (nums1[i] > nums2[j]){\n j++;\n } else {\n i++;\n // j++;\n }\n }\n while(i < n){\n // System.out.println("avy" + nums1[i]);\n if(x < 1 || nums1[i] != arr.get(0).get(x-1)){\n arr.get(0).add(nums1[i]);\n x++;\n }\n i++;\n }\n\n i = 0; j = 0;\n while(i < n && j < m){\n if(nums2[j] < nums1[i]){\n if(y < 1 || nums2[j] != arr.get(1).get(y-1)){\n arr.get(1).add(nums2[j]);\n y++;\n }\n j++;\n } else if (nums2[j] > nums1[i]){\n i++;\n } else {\n // i++;\n j++;\n }\n }\n\n while(j < m){\n if(y < 1 || nums2[j] != arr.get(1).get(y-1)){\n arr.get(1).add(nums2[j]);\n y++;\n }\n j++;\n }\n\n return arr;\n }\n}\n\n```
4
0
['Two Pointers', 'Sorting', 'Java']
2
find-the-difference-of-two-arrays
Beats 100% of users || Step by Step Explain || Brute Force Approach || Easy to Understand ||
beats-100-of-users-step-by-step-explain-j0u11
Abhiraj Pratap Singh\n\n---\n\n\n# Intuition\n Describe your first thoughts on how to solve this problem. \n- The goal appears to be finding the difference betw
abhirajpratapsingh
NORMAL
2024-01-05T19:17:02.446577+00:00
2024-01-05T19:17:02.446635+00:00
107
false
# Abhiraj Pratap Singh\n\n---\n\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- The goal appears to be finding the difference between two sets of integers represented by vectors nums1 and nums2. The difference is computed as the elements present in nums1 but not in nums2 (ans1) and the elements present in nums2 but not in nums1 (ans2).\n\n---\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. The code uses sets (s1 and s2) to convert vectors nums1 and nums2 into sets to efficiently perform set operations.\n2. It then calculates the set differences using set_difference between s1 and s2 (ans1) and between s2 and s1 (ans2).\n3. The result is stored in vectors v1 and v2.\n4. Finally, the function returns a vector of vectors containing the results v1 and v2.\n\n---\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n**Time complexity: O(m+n),** where m and n are the sizes of nums1 and nums2, respectively. The set differences take linear time.\n\n---\n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n**Space complexity: O(m+n),** where m and n are the sizes of nums1 and nums2, respectively. The space is used to store sets and vectors.\n\n---\n\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) \n {\n set<int>s1(nums1.begin(),nums1.end());\n set<int>s2(nums2.begin(),nums2.end());\n set<int>ans1,ans2;\n vector<int>v1;\n vector<int>v2;\n\n set_difference(s1.begin(),s1.end(),s2.begin(),s2.end(),inserter(ans1,ans1.end()));\n set_difference(s2.begin(),s2.end(),s1.begin(),s1.end(),inserter(ans2,ans2.end()));\n\n for(auto it :ans1)\n v1.push_back(it);\n for(auto it :ans2)\n v2.push_back(it);\n return {v1,v2};\n }\n};\n```\n\n---\n\n# IF YOU LIKE THE SOLUTION PLEASE UPVOTE IT....\n\n![discord-discordgifemoji.gif](https://assets.leetcode.com/users/images/ffbca146-9aea-40ba-8ebc-8b8dfc61b5f2_1704482170.9687743.gif)\n![fucking-die-redditor-stupid-cuck-funny-cat.gif](https://assets.leetcode.com/users/images/32a64a50-aa40-4f39-a01f-290e651bb458_1704482174.0209467.gif)\n
4
0
['Array', 'Hash Table', 'Ordered Set', 'C++']
0
find-the-difference-of-two-arrays
C++ || OPTIMISED EASY TO UNDERSTAND
c-optimised-easy-to-understand-by-ganesh-hmwh
Code\n\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n unordered_map<int,int> mp;\n
ganeshkumawat8740
NORMAL
2023-05-11T16:35:32.640441+00:00
2023-05-11T16:35:32.640491+00:00
888
false
# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n unordered_map<int,int> mp;\n vector<vector<int>> v(2);\n for(auto &i: nums1){\n if(mp.count(i)==0)mp[i]++;\n }\n for(auto &i: nums2){\n if(mp.count(i)){\n if(mp[i])mp[i]--;\n }else{\n mp[i]--;\n }\n }\n for(auto &i: mp){\n if(i.second>0)v[0].push_back(i.first);\n else if(i.second<0) v[1].push_back(i.first);\n }\n return v;\n }\n};\n```
4
0
['Array', 'Hash Table', 'C++']
1
find-the-difference-of-two-arrays
One line solution = ( [ TS, JS ] ) => Easy;
one-line-solution-ts-js-easy-by-deleted_-9ko5
\nfunction findDifference(a: number[], b: number[]): number[][] {\n return [[...new Set(a.filter(e=>!b.includes(e)))],[...new Set(b.filter(e =>!a.includes(e)))
deleted_user
NORMAL
2023-05-03T10:41:16.263123+00:00
2023-05-03T10:41:16.263152+00:00
597
false
```\nfunction findDifference(a: number[], b: number[]): number[][] {\n return [[...new Set(a.filter(e=>!b.includes(e)))],[...new Set(b.filter(e =>!a.includes(e)))]];\n};\n```
4
0
['TypeScript', 'JavaScript']
2
find-the-difference-of-two-arrays
Easy Hashmap solution with C++
easy-hashmap-solution-with-c-by-ayush_ba-8we3
\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n \n map<int,int> mp1;\n map<
Ayush_Balodi
NORMAL
2023-05-03T08:47:29.380033+00:00
2023-05-04T20:09:36.327641+00:00
784
false
```\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n \n map<int,int> mp1;\n map<int,int> mp2;\n vector<vector<int>> v(2);\n \n\t\t// map to store the occurrence of the elements in nums1\n for( auto x:nums1 ){\n mp1[x]++;\n }\n \n\t\t// map to store the occurenece of the elements in nums2\n for( auto x:nums2 ){\n mp2[x]++;\n }\n \n\t\t// traversing in the nums1 vector\n for( auto x:nums1 ){\n\t\t\t\n\t\t\t// checking the map of nums 2 for the elements which are in nums1 and updating that found value with -1 to avoid repititions\n if( mp2.find(x) == mp2.end() and mp2[x] != -1 )\n { \n mp2[x]--;\n v[0].push_back(x);\n } \n }\n\t\t\n\t\t// traversing the nums 2 vector\n for( auto x:nums2 ){\n\t\t\n\t\t\t// checking the map of nums1 for the elements which are in nums2 and updating that found value with -1 to avoid repititions\n if( mp1.find(x) == mp1.end() and mp1[x] != -1 )\n {\n mp1[x]--;\n v[1].push_back(x);\n } \n }\n\t\t\n\t\t// returning the vector of vector contaning the required elements.\n return v;\n }\n \n};\n```
4
0
['Array', 'C', 'C++']
2
find-the-difference-of-two-arrays
C#: faster than 85%
c-faster-than-85-by-igor0-afff
Intuition\nUse HashSet and its methods.\n\n# Approach\nUse HashSet and its method ExceptWith to except items from the other array.\n\n# Complexity\n- Time compl
igor0
NORMAL
2023-05-03T08:42:28.069412+00:00
2023-05-03T08:42:28.069461+00:00
938
false
# Intuition\nUse HashSet<int> and its methods.\n\n# Approach\nUse HashSet<int> and its method ExceptWith to except items from the other array.\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\npublic class Solution {\n public IList<IList<int>> FindDifference(int[] nums1, int[] nums2) {\n var set1 = new HashSet<int>(nums1);\n var set2 = new HashSet<int>(nums2);\n set2.ExceptWith(nums1);\n set1.ExceptWith(nums2);\n return new List<IList<int>>{set1.ToList(), set2.ToList()};\n }\n}\n```
4
0
['Hash Table', 'C#']
1
find-the-difference-of-two-arrays
One lIne of Code Superb Questions--->Python3
one-line-of-code-superb-questions-python-69kp
1. Using sets Concept\n\nclass Solution:\n def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:\n return [set(nums1)-set(n
GANJINAVEEN
NORMAL
2023-05-03T05:57:09.328437+00:00
2023-05-03T05:59:29.585137+00:00
556
false
# 1. Using sets Concept\n```\nclass Solution:\n def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:\n return [set(nums1)-set(nums2),set(nums2)-set(nums1)]\n```\n# -------------------------------------or-------------------------------------------\n```\nclass Solution:\n def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:\n list1=set(nums1)-set(nums2)\n list2=set(nums2)-set(nums1)\n return [list1,list2]\n```\n# 2. Python Solution\n```\nclass Solution:\n def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:\n list1=[]\n list2=[]\n list3=[]\n for i in nums1:\n if i in nums2:\n continue\n else:\n list2.append(i)\n for j in nums2:\n if j in nums1:\n continue\n else:\n list3.append(j)\n list1.append(list(set(list2)))\n list1.append(list(set(list3)))\n return list1\n\n```\n# please upvote me it would encourage me alot\n
4
0
['Python3']
1
find-the-difference-of-two-arrays
✅C++✅Explanation ✅Faster than100%
cexplanation-faster-than100-by-dhairyash-wdzp
The time complexity of code is O(n1 + n2), where n1 and n2 are the sizes of the input arrays nums1 and nums2 respectively. \n\nThis is because we are iterating
dhairyashiil
NORMAL
2023-05-03T05:29:43.214068+00:00
2023-05-03T05:29:43.214112+00:00
374
false
The time complexity of code is O(n1 + n2), where n1 and n2 are the sizes of the input arrays nums1 and nums2 respectively. \n\nThis is because we are iterating through each element of nums1 and nums2 once to populate the map, and then iterating through each element of nums2 and nums1 once again to append elements to the answer vectors.\n\nThis time complexity is optimal since we must look at every element in both arrays to determine the differences. \n\nThe space complexity is O(n1), where n1 is the size of nums1, since we are storing the elements of nums1 in a map.\n\n# C++ Code\n```\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n int n1 = nums1.size();\n int n2 = nums2.size();\n \n vector<int> ans1;\n vector<int> ans2;\n \n unordered_map<int, int> m;\n // 1 -> if it is present only in nums1\n // 2 -> if it is present only in nums2\n // 3 -> if it is present in both nums1 & nums2\n // 4 -> after considering that element in \'ans\', so that we have only distinct integers\n \n // loop through nums1 and mark all elements as \'1\'\n for(int i=0; i<n1; i++) {\n m[nums1[i]] = 1;\n }\n \n // loop through nums2\n for(int i=0; i<n2; i++) {\n // if the element is present in nums1\n if(m[nums2[i]] == 1) {\n m[nums2[i]] = 3; // mark as \'3\' since it\'s in both arrays\n }\n else {\n // if the element is not present in nums1 or it\'s already been added to ans2\n if(m[nums2[i]] != 3) {\n if (m[nums2[i]] != 2) { // if it\'s not been added to ans2 yet\n ans2.push_back(nums2[i]); // add to ans2\n m[nums2[i]] = 2; // mark as \'2\' since it\'s only in nums2\n }\n }\n }\n }\n \n // loop through nums1 again\n for(int i=0; i<n1; i++) {\n if(m[nums1[i]] == 1) { // if it\'s only in nums1\n ans1.push_back(nums1[i]); // add to ans1\n m[nums1[i]] = 4; // mark as \'4\' so that we don\'t add duplicates next time\n }\n }\n \n return {ans1, ans2}; // return the two arrays\n }\n};\n\n```\n\n### ***If you find this helpful, Please Upvote \uD83D\uDD3C , Thank You !***\n\n![Meme Code Run.jpg](https://assets.leetcode.com/users/images/f4cb6249-8d5d-4126-9abe-0f39c0900405_1682308842.2299054.jpeg)
4
0
['Hash Table', 'C++']
0
find-the-difference-of-two-arrays
Day 123 || Hash Table || O(m+n) time and O(max(m,n)) space
day-123-hash-table-omn-time-and-omaxmn-s-2vez
\n\n# Code :\nC++ []\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n unordered_set<int> s1
singhabhinash
NORMAL
2023-05-03T03:26:52.105823+00:00
2023-05-03T03:26:52.105869+00:00
713
false
\n\n# Code :\n```C++ []\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n unordered_set<int> s1, s2;\n vector<vector<int>> answer(2);\n for (auto num : nums1)\n s1.insert(num);\n for (auto num : nums2)\n s2.insert(num);\n for (auto num : s1) {\n if (s2.find(num) == s2.end()) {\n answer[0].push_back(num);\n }\n }\n for (auto num : s2) {\n if (s1.find(num) == s1.end()) {\n answer[1].push_back(num);\n }\n }\n return answer;\n }\n};\n```\n\n# Time Complexity and Space Complexity:\n- **Time Complexity :** **O(m + n)**, where m is the size of nums1 and n is the size of nums2\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- **Space Complexity :** **O(max(m, n))**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->
4
0
['Hash Table', 'C++']
1
find-the-difference-of-two-arrays
Python short 1-liner. Functional programming.
python-short-1-liner-functional-programm-3ncg
Approach\nConvert lists into sets and take a set difference.\n\n# Complexity\n- Time complexity: O(n1 + n2)\n\n- Space complexity: O(n1 + n2)\n\nwhere,\nn1 is l
darshan-as
NORMAL
2023-05-03T03:22:32.218775+00:00
2023-05-03T03:22:32.218804+00:00
1,000
false
# Approach\nConvert lists into sets and take a set difference.\n\n# Complexity\n- Time complexity: $$O(n1 + n2)$$\n\n- Space complexity: $$O(n1 + n2)$$\n\nwhere,\n`n1 is length of nums1`,\n`n2 is length of nums2`.\n\n# Code\n```python\nclass Solution:\n def findDifference(self, nums1: list[int], nums2: list[int]) -> list[list[int]]:\n return (lambda a, b: [a - b, b - a])(set(nums1), set(nums2))\n\n\n```
4
0
['Array', 'Hash Table', 'Python', 'Python3']
2
find-the-difference-of-two-arrays
c# 2 line solution, faster than 92%
c-2-line-solution-faster-than-92-by-vinu-oxbi
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
vinuaqua4u
NORMAL
2023-05-03T01:37:55.377749+00:00
2023-05-03T01:37:55.377779+00:00
1,502
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 IList<IList<int>> FindDifference(int[] nums1, int[] nums2) {\n HashSet<int> h1 = new HashSet<int>(nums1), h2 = new HashSet<int>(nums2);\n\n return new List<IList<int>> { \n h1.Where(x => !h2.Contains(x)).ToList<int>(), \n h2.Where(x => !h1.Contains(x)).ToList<int>() \n };\n }\n}\n```
4
0
['C#']
0
find-the-difference-of-two-arrays
Easiest Approach
easiest-approach-by-l30xl1u-ss4p
Idea\n- Working with arrays is troublesome since they are ordered so instead we convert them to sets.\n- In particular, ordered sets would require higher time c
L30XL1U
NORMAL
2023-05-03T00:32:48.348044+00:00
2023-05-03T00:41:55.544751+00:00
1,214
false
# Idea\n- Working with arrays is troublesome since they are ordered so instead we convert them to sets.\n- In particular, ordered sets would require higher time complexity so we use unordered sets which accomplish the same task but faster.\n- Using sets also solves any issues with duplicate integers within an array. \n- We will iterate through `set1` to check whether `set2` contains any common elements. \n- Every common element we find will go into `set3`.\n- We do not directly remove from `set1` and`set2` because this messes up the for loop iterations. \n- Finally, we iterate through `set3` which is all the common elements and we remove them from both `set1` and `set2`. \n- Now, `set1` and `set2` are left with only **distinct** elements.\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n // Initialize a set for each array and a common set\n unordered_set<int> set1(nums1.begin(), nums1.end());\n unordered_set<int> set2(nums2.begin(), nums2.end());\n unordered_set<int> set3;\n\n // Find common values of each set\n for (auto p : set1){\n if (set2.find(p) != set2.end()){\n set3.insert(p);\n }\n }\n\n // Remove common elements from both sets\n for (auto p : set3){\n set1.erase(p), set2.erase(p);\n }\n\n // Translate sets into array answer\n vector<vector<int>> res;\n res.push_back(vector<int>(set1.begin(), set1.end()));\n res.push_back(vector<int>(set2.begin(), set2.end()));\n return res;\n }\n};\n```\n### If this was helpful, please leave an upvote! Thank you :)
4
0
['C++']
2
find-the-difference-of-two-arrays
Java | HashSet | Beats > 93% | Simple code
java-hashset-beats-93-simple-code-by-jud-eunj
Complexity\n- Time complexity: O(m+n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(max(m,n))\n Add your space complexity here, e.g. O(n)
judgementdey
NORMAL
2023-05-03T00:15:43.761757+00:00
2023-05-04T18:04:13.723610+00:00
482
false
# Complexity\n- Time complexity: $$O(m+n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(max(m,n))$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {\n var set1 = new HashSet<Integer>();\n var set2 = new HashSet<Integer>();\n var common = new HashSet<Integer>();\n\n for (var n : nums1)\n set1.add(n);\n\n for (var n : nums2) {\n if (set1.contains(n)) {\n set1.remove(n);\n common.add(n);\n } else if (!common.contains(n)) {\n set2.add(n);\n }\n } \n return new ArrayList<>() {{\n add(new ArrayList<>(set1));\n add(new ArrayList<>(set2));\n }};\n }\n}\n```\nIf you like my solution, please upvote it!
4
0
['Array', 'Hash Table', 'Java']
0
find-the-difference-of-two-arrays
2215. Find the Difference of Two Arrays || Array || DSA
2215-find-the-difference-of-two-arrays-a-n9me
Intuition\nUsing Set objects allows us to efficiently store only the unique elements in each input array, eliminating duplicates and reducing the overall search
singh-csm
NORMAL
2023-03-18T19:05:28.933986+00:00
2023-03-18T19:05:28.934030+00:00
825
false
# Intuition\nUsing Set objects allows us to efficiently store only the unique elements in each input array, eliminating duplicates and reducing the overall search time.\nFiltering the elements using .filter() method allows us to easily find the differences between the two sets by checking if each element is in one set but not the other.\nUsing an array csm to store the difference arrays allows us to easily return both arrays as a single value.\n\n# Approach\nWe first create two Set objects set1 and set2 from the input arrays nums1 and nums2, respectively, to store the unique elements in each array.\nWe then create an empty array csm to store the two difference arrays.\nTo find the elements that are in set1 but not in set2, we filter the elements in set1 by checking if they are not in set2 using the .filter() method, and assign the filtered array to csm[0].\nSimilarly, to find the elements that are in set2 but not in set1, we filter the elements in set2 by checking if they are not in set1, and assign the filtered array to csm[1].\nFinally, we return the csm array containing the two difference arrays.\n\n# Complexity\n- Time complexity: O(n), where n is the length of the longer input array. This is because creating the two Set objects takes O(n) time each, and filtering the arrays using .filter() takes O(n) time each. Thus, the overall time complexity is O(n + n + n + n) = O(4n) = O(n).\n\n- Space complexity: O(n), where n is the total number of unique elements in both input arrays. This is because we create two Set objects to store the unique elements in the input arrays, and the maximum size of each Set is n (when both input arrays have all unique elements). We also create an array csm to store the two difference arrays, which has a maximum size of 2n. Thus, the overall space complexity is O(2n + n) = O(3n) = O(n).\n\n# Code\n```\n\nvar findDifference = function(nums1, nums2) {\n let set1 = new Set(nums1);\n let set2 = new Set(nums2);\n let csm=[];\n csm[0]= [...set1].filter(x => !set2.has(x));\n csm[1]= [...set2].filter(x => !set1.has(x));\n return csm\n};\n\n```
4
0
['JavaScript']
0
find-the-difference-of-two-arrays
C++ Solution || Two-Pointers || Unordered Set
c-solution-two-pointers-unordered-set-by-8plc
Approach 1: Sorting + Two Pointers\nTime Complexity: max(O(NlogN), O(MlogM)), M, N are size of arrays\n\nclass Solution {\npublic:\n vector<vector<int>> find
aniketk2k
NORMAL
2023-03-12T12:31:43.956511+00:00
2023-03-12T12:31:43.956544+00:00
1,130
false
**Approach 1: Sorting + Two Pointers**\n**Time Complexity: max(O(NlogN), O(MlogM))***, M, N are size of arrays*\n```\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n sort(nums1.begin(), nums1.end());\n sort(nums2.begin(), nums2.end());\n \n vector<int> v1;\n vector<int> v2;\n \n int n = nums1.size();\n int m = nums2.size();\n int i = 0;\n int j = 0;\n \n while(i < n && j < m){\n while(i < n-1 && nums1[i] == nums1[i+1])\n i++;\n while(j < m-1 && nums2[j] == nums2[j+1])\n j++;\n if(nums1[i] < nums2[j])\n v1.push_back(nums1[i++]);\n else if(nums1[i] > nums2[j])\n v2.push_back(nums2[j++]);\n else{\n i++;\n j++;\n }\n }\n \n while(i < n){\n while(i < n-1 && nums1[i] == nums1[i+1])\n i++;\n v1.push_back(nums1[i++]);\n }\n \n while(j < m){\n while(j < m-1 && nums2[j] == nums2[j+1])\n j++;\n v2.push_back(nums2[j++]);\n }\n \n return {v1, v2};\n }\n};\n```\n\n**Apporach 2: Using Unordered set**\n**Time Complexity: max(O(N), O(M))**\n```\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n unordered_set<int> s1(nums1.begin(), nums1.end());\n unordered_set<int> s2(nums2.begin(), nums2.end());\n \n vector<int> v1, v2;\n for(auto num: s1)\n if(!s2.count(num))\n v1.push_back(num);\n \n for(auto num: s2)\n if(!s1.count(num))\n v2.push_back(num);\n \n return {v1, v2};\n }\n};\n```\n\nDo upvote if this helps.
4
0
['Two Pointers', 'C', 'Ordered Set', 'C++']
0
find-the-difference-of-two-arrays
C++ set solution
c-set-solution-by-sethiyashristi20-tb8t
class Solution {\npublic:\n vector> findDifference(vector& nums1, vector& nums2) {\n\t\n vector>ans;\n vectords;\n vectords2;\n u
sethiyashristi20
NORMAL
2022-05-14T17:11:16.337068+00:00
2022-05-14T17:11:16.337110+00:00
315
false
class Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n\t\n vector<vector<int>>ans;\n vector<int>ds;\n vector<int>ds2;\n unordered_set<int>s;\n unordered_set<int>s1;\n for(auto &it:nums1)s.insert(it);\n for(auto &it:nums2)s1.insert(it);\n for(auto it:s1)\n {\n if(s.find(it)==s.end())ds.push_back(it);\n }\n for(auto it:s)\n {\n if(s1.find(it)==s1.end())ds2.push_back(it);\n }\n ans.push_back(ds2);\n ans.push_back(ds);\n return ans;\n }\n};\n**Please do upvote if you liked it!!**
4
0
['C']
1
find-the-difference-of-two-arrays
Elixir Solution Using MapSet
elixir-solution-using-mapset-by-stackcat-xaox
elixir\ndefmodule Solution do\n @spec find_difference(nums1 :: [integer], nums2 :: [integer]) :: [[integer]]\n def find_difference(nums1, nums2) do\n s1 =
stackcats
NORMAL
2022-04-07T03:50:04.752692+00:00
2022-04-07T03:50:04.752738+00:00
70
false
```elixir\ndefmodule Solution do\n @spec find_difference(nums1 :: [integer], nums2 :: [integer]) :: [[integer]]\n def find_difference(nums1, nums2) do\n s1 = MapSet.new(nums1)\n s2 = MapSet.new(nums2)\n [MapSet.difference(s1, s2) |> Enum.to_list(), MapSet.difference(s2, s1) |> Enum.to_list()]\n end\nend\n```
4
0
['Elixir']
0
find-the-difference-of-two-arrays
Golang HashSet(actually HashMap)
golang-hashsetactually-hashmap-by-ernest-qkwa
golang why don\'t we have a set datastructure\ngo\nfunc findDifference(nums1 []int, nums2 []int) [][]int {\n s1,s2:=make(map[int]bool),make(map[int]bool)\n
ernestlin
NORMAL
2022-03-27T08:30:03.870654+00:00
2022-03-27T08:31:10.348273+00:00
611
false
[golang why don\'t we have a set datastructure](https://stackoverflow.com/questions/34018908/golang-why-dont-we-have-a-set-datastructure)\n```go\nfunc findDifference(nums1 []int, nums2 []int) [][]int {\n s1,s2:=make(map[int]bool),make(map[int]bool)\n for _,n:=range(nums1){\n s1[n]=true\n }\n for _,n:=range(nums2){\n s2[n]=true\n }\n res:=make([][]int,2)\n for k,_:=range s1{\n if _,ok:=s2[k];!ok{\n res[0]=append(res[0],k)\n }\n }\n for k,_:=range s2{\n if _,ok:=s1[k];!ok{\n res[1]=append(res[1],k)\n }\n }\n return res\n}\n```
4
0
['Go']
1
find-the-difference-of-two-arrays
Time -O(n) || Space -O(n) || C++ Solution
time-on-space-on-c-solution-by-shishir_s-zxhl
\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n unordered_map<int,int> umap1;\n un
Shishir_Sharma
NORMAL
2022-03-27T04:09:54.571027+00:00
2022-03-27T04:09:54.571063+00:00
899
false
```\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n unordered_map<int,int> umap1;\n unordered_map<int,int> umap2;\n vector<vector<int>> result(2);\n for(int i=0;i<nums1.size();i++)\n {\n umap1[nums1[i]]=1;\n }\n for(int i=0;i<nums2.size();i++)\n {\n umap2[nums2[i]]=1;\n }\n set<int> st;\n for(int i=0;i<nums1.size();i++)\n {\n if(umap2[nums1[i]]==0)\n {\n st.insert(nums1[i]);\n }\n }\n for (auto itr = st.begin(); itr != st.end(); itr++) \n {\n int t=*itr;\n result[0].push_back(t);\n }\n \n set<int> st1;\n for(int i=0;i<nums2.size();i++)\n {\n if(umap1[nums2[i]]==0)\n {\n st1.insert(nums2[i]);\n }\n }\n for (auto itr = st1.begin(); itr != st1.end(); itr++) \n {\n int t=*itr;\n result[1].push_back(t);\n }\n return result; \n \n }\n};\n```\n**Like it? Please Upvote ;-)**
4
0
['C', 'C++']
0
find-the-difference-of-two-arrays
[Python3] Simple solution using set
python3-simple-solution-using-set-by-het-6ka5
\n def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:\n s1 = set(nums1)\n s2 = set(nums2)\n \n nums
hetvigarg
NORMAL
2022-03-27T04:03:17.758847+00:00
2022-03-27T04:04:29.536103+00:00
881
false
\n def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:\n s1 = set(nums1)\n s2 = set(nums2)\n \n nums1 = list(s1)\n nums2 = list(s2)\n \n s = []\n for i in range(len(nums1)):\n if nums1[i] not in s2:\n s.append(nums1[i])\n d = [] \n for i in range(len(nums2)):\n if nums2[i] not in s1:\n d.append(nums2[i])\n \n res = []\n res.append(s)\n res.append(d)\n return res
4
0
['Ordered Set', 'Python', 'Python3']
0
find-the-difference-of-two-arrays
Find the Difference of Two Arrays
find-the-difference-of-two-arrays-by-utk-851z
IntuitionWe need to find unique elements in each of the two given lists. Using sets helps eliminate duplicates and allows efficient lookups.Approach Convert num
UtkarshJi
NORMAL
2025-02-19T18:05:23.433904+00:00
2025-02-19T18:05:23.433904+00:00
201
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> We need to find unique elements in each of the two given lists. Using sets helps eliminate duplicates and allows efficient lookups. # Approach <!-- Describe your approach to solving the problem. --> 1. Convert nums1 and nums2 into sets (set1 and set2) to remove duplicates. 2. Iterate through set1, adding elements not present in set2 to list1. 3. Iterate through set2, adding elements not present in set1 to list2. 4. Return {list1, list2}. # Complexity - Time complexity: O(nlogn+mlogm) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(n+m) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] // class Solution { // public: // vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) { // vector<vector<int>> ans; // unordered_set<int> set1 (nums1.begin(), nums1.end()); // unordered_set<int> set2 (nums2.begin(), nums2.end()); // vector<int> list1, list2; // for(int num: set1){ // if(set2.find(num) == set2.end()) list1.push_back(num); // } // for(int num: set2){ // if(set1.find(num) == set1.end()) list2.push_back(num); // } // return {list1, list2}; // } // }; class Solution { public: vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) { set<int> set1 (nums1.begin(), nums1.end()); set<int> set2 (nums2.begin(), nums2.end()); vector<int> list1, list2; for(int num: set1){ if(set2.find(num) == set2.end()) list1.push_back(num); } for(int num: set2){ if(set1.find(num) == set1.end()) list2.push_back(num); } return {list1, list2}; } }; ```
3
0
['Array', 'Hash Table', 'Ordered Set', 'C++']
0
find-the-difference-of-two-arrays
C++ | 100% | Easiest | O(n+m)
c-100-easiest-onm-by-sushilbajpai-9i7z
IntuitionThe problem requires finding the distinct elements in each of the two arrays that are not present in the other array. My initial thought is to use hash
sushilbajpai
NORMAL
2025-02-14T16:53:28.120582+00:00
2025-02-14T16:53:28.120582+00:00
425
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> The problem requires finding the distinct elements in each of the two arrays that are not present in the other array. My initial thought is to use hash maps to efficiently track the presence of elements in both arrays and then identify the unique elements for each array. # Approach <!-- Describe your approach to solving the problem. --> - Use Hash Maps: Create two hash maps (mp1 and mp2) to store the frequency of elements in nums1 and nums2, respectively. - Populate Hash Maps: Iterate through nums1 and nums2 to populate the hash maps with the counts of each element. - Identify Unique Elements: Iterate through the keys in mp1 and check if they are not present in mp2. Similarly, iterate through the keys in mp2 and check if they are not present in mp1. - Store Results: Store the unique elements for nums1 in ans1 and for nums2 in ans2. - Return Result: Return the results as a vector of vectors containing ans1 and ans2. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(n+m) - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(n+m) # Code ```cpp [] class Solution { public: vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) { vector<vector<int>> ans; unordered_map<int, int> mp1, mp2; int n1=nums1.size(); int n2=nums2.size(); for(int i=0; i<n1; i++){ mp1[nums1[i]]++; } for(int i=0; i<n2; i++){ mp2[nums2[i]]++; } vector<int> ans1, ans2; for(auto it: mp1){ if(!mp2[it.first]){ ans1.push_back(it.first); } } for(auto it: mp2){ if(!mp1[it.first]){ ans2.push_back(it.first); } } ans.push_back(ans1); ans.push_back(ans2); return ans; } }; ```
3
0
['C++']
0
find-the-difference-of-two-arrays
Easy solution in Python💯✅
easy-solution-in-python-by-uwwcpcfmx5-rtpp
IntuitionFirst remove duplicates using set() and then iterate through each list to find elements not present in the other. These unique elements are appended to
UWWcPcfMx5
NORMAL
2025-01-24T13:39:10.009350+00:00
2025-01-27T04:03:27.826079+00:00
842
false
# Intuition First remove duplicates using set() and then iterate through each list to find elements not present in the other. These unique elements are appended to their respective result lists. # Complexity - Time complexity:O(N^2) as we are using two for loops to check <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity:O(N) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]: answer=[[],[]] x=list(set(nums1)) y=list(set(nums2)) for i in range(len(x)): if x[i] not in y: answer[0].append(x[i]) for i in range(len(y)): if y[i] not in x: answer[1].append(y[i]) return answer ``` ![dfc8570d-35b1-4f1c-9c58-8835758be62c_1690230597.7965565.png](https://assets.leetcode.com/users/images/de350e74-5e53-4375-aae6-b842bddd6d20_1737725912.5466192.png)
3
0
['Python3']
1
find-the-difference-of-two-arrays
simple and easy understanding c++ code
simple-and-easy-understanding-c-code-by-a5vmi
\ncpp []\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n int n=nums1.size();\n int
sampathkumar718
NORMAL
2024-09-26T13:24:01.798702+00:00
2024-09-26T13:24:01.798727+00:00
726
false
\n```cpp []\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n int n=nums1.size();\n int m=nums2.size();\n vector<vector<int>>arr1(2);\n unordered_set<int>a(nums1.begin(),nums1.end());\n unordered_set<int>b(nums2.begin(),nums2.end());\n for(int i:a){\n if(b.find(i)==b.end()){\n arr1[0].push_back(i);\n }\n }\n for(int j:b){\n if(a.find(j)==a.end()){\n arr1[1].push_back(j);\n }\n }\n return arr1;\n \n }\n};\n```
3
0
['C++']
1
find-the-difference-of-two-arrays
BEATS MEMORY 91.23 % But Time LESS !
beats-memory-9123-but-time-less-by-inava-kqj8
Intuition\nTo find the unique elements in two arrays that are not present in the other, we can first sort both arrays and remove duplicates. After that, we can
inavadeep1205
NORMAL
2024-09-19T04:33:42.455367+00:00
2024-09-19T04:33:42.455398+00:00
1,760
false
# Intuition\nTo find the unique elements in two arrays that are not present in the other, we can first sort both arrays and remove duplicates. After that, we can check each element of one array against the other to identify the differences.\n\n# Approach\n1.) Sort both input arrays and remove duplicates using std::unique.\n2.) For each element in the first array, check if it exists in the second array. If it does not exist, add it to the result.\n3.) Repeat the process for the second array.\n4.) Return a vector containing the unique elements from both arrays.\n\n# Complexity\n- Time complexity: \n**O(nlogn)** (for sorting)\n\n- Space complexity:\n**O(n)** (for storing the unique elements)\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& arr1, vector<int>& arr2) {\n \n \n sort(arr1.begin(), arr1.end());\n sort(arr2.begin(), arr2.end());\n \n auto it1 = unique(arr1.begin(), arr1.end());\n auto it2 = unique(arr2.begin(), arr2.end());\n \n arr1.erase(it1, arr1.end());\n arr2.erase(it2, arr2.end());\n \n vector<int> dp;\n vector<int> dp2;\n \n \n for(auto i : arr1){\n auto it = find(arr2.begin(), arr2.end(), i);\n if(it != arr2.end()){\n NULL;\n }\n else{\n dp.push_back(i);\n }\n }\n \n for(auto i : arr2){\n auto it = find(arr1.begin(), arr1.end(), i);\n if(it != arr1.end()){\n NULL;\n }\n else{\n dp2.push_back(i);\n }\n }\n \n return {dp,dp2};\n\n }\n};\n```
3
0
['C++']
1
find-the-difference-of-two-arrays
Easy C++ Solution || unordered_set
easy-c-solution-unordered_set-by-yogeshw-xccs
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
yogeshwaribisht21
NORMAL
2024-08-24T05:39:02.541932+00:00
2024-08-24T05:39:02.541970+00:00
258
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n unordered_set<int>s1(nums1.begin(),nums1.end());\n unordered_set<int>s2(nums2.begin(),nums2.end());\n vector<vector<int>>ans;\n vector<int>v;\n for(auto &x :s1)\n {\n if(s2.find(x)==s2.end())\n {\n v.push_back(x);\n }\n }\n ans.push_back(v);\n v.clear();\n for(auto &x :s2)\n {\n if(s1.find(x)==s1.end())\n {\n v.push_back(x);\n }\n }\n ans.push_back(v);\n return ans;\n\n }\n};\n```
3
0
['Array', 'Hash Table', 'C++']
1
find-the-difference-of-two-arrays
clean solution
clean-solution-by-sanshubh-du96
Intuition\n Describe your first thoughts on how to solve this problem. \nSince we are dealing with distinct integers, a set is applicable. Creating a set as wel
sanshubh
NORMAL
2024-04-29T03:26:14.109122+00:00
2024-04-29T03:26:29.890794+00:00
1,093
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSince we are dealing with distinct integers, a set is applicable. Creating a set as well as a list to add the distict elements to is ideal after which we can simply combine it with the second case and return the 2-dimensional list. \n\n\n# Code\n```\nclass Solution:\n def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:\n s1 = set(nums1)\n s2 = set(nums2)\n arr1 = []\n arr2 = []\n for i in range(len(nums1)):\n if nums1[i] not in s2:\n arr1.append(nums1[i])\n s2.add(nums1[i])\n for i in range(len(nums2)):\n if nums2[i] not in s1:\n arr2.append(nums2[i])\n s1.add(nums2[i])\n return [arr1, arr2]\n```
3
0
['Python3']
1
find-the-difference-of-two-arrays
Vector Difference Finder C++
vector-difference-finder-c-by-stella_win-2kcq
Intuition\nThe intuition is to find the elements that are present in one vector (nums1) but not in the other vector (nums2). \n\n# Approach\n1. Counting Occurre
Stella_Winx
NORMAL
2024-03-18T10:05:52.384857+00:00
2024-03-18T10:05:52.384887+00:00
13
false
# Intuition\nThe intuition is to find the elements that are present in one vector (nums1) but not in the other vector (nums2). \n\n# Approach\n1. Counting Occurrences: Two unordered_maps (m and mp) are used to count the occurrences of elements in nums1 and nums2 respectively.\n This step helps identify which elements are unique to each vector.\n\n2. Identifying Unique Elements: Two vectors (v1 and v2) are initialized to store elements unique to nums2 and nums1 respectively. \n This is achieved by iterating through one vector and checking if each element is present in the other vector\'s count map. If not, the element is added to the corresponding unique elements vector.\n\n3. Sorting and Removing Duplicates: Both v1 and v2 are sorted to prepare for removing duplicates. \n The unique algorithm is then applied to remove consecutive duplicate elements from each vector.\n\n4. Constructing Result: The unique elements vectors (v1 and v2) are then pushed into a 2D vector res, where v1 represents elements unique to nums2 and v2 represents elements unique to nums1.\n\n The 2D vector res containing the unique elements from both vectors is returned.\n\n# Complexity\n- Time complexity:\nO(n + m)\n\n- Space complexity:\nO(n + m)\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n unordered_map<int,int>m;\n unordered_map<int,int>mp;\n\n for(int i=0;i<nums2.size();i++)\n {\n mp[nums2[i]]++;\n }\n vector<int>v2;\n for(auto j:nums1)\n {\n if(mp.find(j)==mp.end())\n {\n v2.push_back(j);//nums1 values\n }\n }\n\n\n for(int i=0;i<nums1.size();i++)\n {\n m[nums1[i]]++;\n }\n vector<int>v1;\n for(auto j:nums2)\n {\n if(m.find(j)==m.end())\n {\n v1.push_back(j);//nums2 values\n }\n }\n sort(v2.begin(),v2.end());\n sort(v1.begin(),v1.end());\n \n v2.erase(unique(v2.begin(),v2.end()),v2.end());\n v1.erase(unique(v1.begin(),v1.end()),v1.end());\n\n vector<vector<int>>res;\n res.push_back(v2);\n res.push_back(v1);\n \n return res;\n }\n};\n```
3
0
['Hash Table', 'C++']
0
find-the-difference-of-two-arrays
Solution in C#
solution-in-c-by-ritaj_zamel-590v
\n# Approach\nThe code finds all distinct numbers that appear in one list but not the other. It achieves this by iterating through each list and checking if the
Ritaj_Zamel
NORMAL
2024-03-12T08:05:40.544227+00:00
2024-03-12T08:05:40.544253+00:00
1,133
false
\n# Approach\nThe code finds all distinct numbers that appear in one list but not the other. It achieves this by iterating through each list and checking if the number exists in the other list and hasn\'t already been added to a collection of distinct numbers for the current list. Finally, it combines these distinct numbers into a single result structure.\n\n# Complexity\n- Time complexity:\n***O(n * m)***\n**Beats 65.54% of users with C#**\n\n- Space complexity:\n***O(n + m)***\n**Beats 95.16% of users with C#**\n\n# Code\n```\npublic class Solution {\n public IList<IList<int>> FindDifference(int[] nums1, int[] nums2) {\n IList<int> distinctNums1 = new List<int>();\n IList<int> distinctNums2 = new List<int>();\n foreach (int i in nums1)\n {\n if(Array.IndexOf(nums2, i) == -1 && !distinctNums1.Contains(i))\n {\n distinctNums1.Add(i);\n }\n }\n foreach (int i in nums2)\n {\n if (Array.IndexOf(nums1, i) == -1 && !distinctNums2.Contains(i))\n {\n distinctNums2.Add(i);\n }\n }\n IList<IList<int>> result = new List<IList<int>>();\n result.Add(distinctNums1);\n result.Add(distinctNums2);\n return result;\n }\n}\n```
3
0
['C#']
0
find-the-difference-of-two-arrays
JavaScript Solution
javascript-solution-by-sahil3554-1qm8
\n# Complexity\n- Time complexity:\nO(n+m)\n\n- Space complexity:\nO(n+m)\n\n# Code\n\n/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @return {
sahil3554
NORMAL
2023-11-29T04:57:20.795511+00:00
2023-11-29T04:57:20.795538+00:00
313
false
\n# Complexity\n- Time complexity:\n$$O(n+m)$$\n\n- Space complexity:\n$$O(n+m)$$\n\n# Code\n```\n/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @return {number[][]}\n */\nvar findDifference = function(nums1, nums2) {\n let num1Set = new Set(nums1);\n let num2Set = new Set(nums2)\n let result=[[],[]];\n \n for(const num of num1Set){\n if(!(num2Set.has(num))){\n result[0].push(num)\n }\n }\n for(const num of num2Set){\n if(!(num1Set.has(num))){\n result[1].push(num)\n }\n }\n return result;\n}\n```
3
0
['JavaScript']
0
find-the-difference-of-two-arrays
C++ and JAVA both solutions using sets (9ms Beats 93.83% of Java sol | 32ms Beats 88.80% of C++ sol)
c-and-java-both-solutions-using-sets-9ms-r20i
Intuition\nThe problem involves finding the differences between two arrays and returning the results in separate lists. My initial thoughts are to use sets to e
surya_26
NORMAL
2023-11-25T13:45:50.281633+00:00
2024-03-18T16:42:31.660626+00:00
566
false
# Intuition\nThe problem involves finding the differences between two arrays and returning the results in separate lists. My initial thoughts are to use sets to efficiently identify unique elements in both arrays.\n\n# Approach\n1. **Set Initialization:**\n - Create two sets, `s1` and `s2`, from the elements of `nums1` and `nums2`, respectively.\n\n2. **Find Differences:**\n - For each element in `s1`, check if it is not present in `s2`. If true, add it to the first result list (`a1`).\n - For each element in `s2`, check if it is not present in `s1`. If true, add it to the second result list (`a2`).\n\n3. **Return Result:**\n - Return a vector (or list in Java) containing the two result lists (`a1` and `a2`).\n\n# Complexity\n- Time complexity:\n - Constructing sets from the arrays has a time complexity of $$O(n)$$, where $$n$$ is the size of the arrays.\n - Iterating through the sets and finding differences also has a time complexity of $$O(n)$$.\n\n- Space complexity:\n - The space complexity is $$O(n)$$, where $$n$$ is the size of the sets. The sets store unique elements from the arrays. The result lists also contribute to the space complexity.\n\n# C++ Code\n```\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2)\n {\n unordered_set<int> s1(nums1.begin(),nums1.end());\n unordered_set<int> s2(nums2.begin(),nums2.end());\n vector<int> a1,a2;\n for(int it:s1)\n if(!s2.contains(it))\n a1.push_back(it);\n for(int it:s2)\n if(!s1.contains(it))\n a2.push_back(it);\n return {a1,a2};\n }\n};\n```\n# Java Code\n```\npublic class Solution {\n public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {\n Set<Integer> set1 = new HashSet<>();\n Set<Integer> set2 = new HashSet<>();\n for (int num : nums1)\n set1.add(num);\n for (int num : nums2)\n set2.add(num);\n List<Integer> a1 = new ArrayList<>();\n List<Integer> a2 = new ArrayList<>();\n for (int num : set1) {\n if (!set2.contains(num)) {\n a1.add(num);\n }\n }\n for (int num : set2) {\n if (!set1.contains(num)) {\n a2.add(num);\n }\n }\n List<List<Integer>> result = new ArrayList<>();\n result.add(a1);\n result.add(a2);\n return result;\n }\n}\n```
3
0
['Array', 'Hash Table', 'C++', 'Java']
0
pacific-atlantic-water-flow
Java BFS & DFS from Ocean
java-bfs-dfs-from-ocean-by-star1993-nwqo
Two Queue and add all the Pacific border to one queue; Atlantic border to another queue.\n2. Keep a visited matrix for each queue. In the end, add the cell visi
star1993
NORMAL
2016-10-09T16:03:17.787000+00:00
2018-10-26T23:28:40.142867+00:00
122,133
false
1. Two Queue and add all the Pacific border to one queue; Atlantic border to another queue.\n2. Keep a visited matrix for each queue. In the end, add the cell visited by two queue to the result.\nBFS: Water flood from ocean to the cell. Since water can only flow from high/equal cell to low cell, add the neighboor cell with height larger or equal to current cell to the queue and mark as visited.\n```\npublic class Solution {\n int[][]dir = new int[][]{{1,0},{-1,0},{0,1},{0,-1}};\n public List<int[]> pacificAtlantic(int[][] matrix) {\n List<int[]> res = new LinkedList<>();\n if(matrix == null || matrix.length == 0 || matrix[0].length == 0){\n return res;\n }\n int n = matrix.length, m = matrix[0].length;\n //One visited map for each ocean\n boolean[][] pacific = new boolean[n][m];\n boolean[][] atlantic = new boolean[n][m];\n Queue<int[]> pQueue = new LinkedList<>();\n Queue<int[]> aQueue = new LinkedList<>();\n for(int i=0; i<n; i++){ //Vertical border\n pQueue.offer(new int[]{i, 0});\n aQueue.offer(new int[]{i, m-1});\n pacific[i][0] = true;\n atlantic[i][m-1] = true;\n }\n for(int i=0; i<m; i++){ //Horizontal border\n pQueue.offer(new int[]{0, i});\n aQueue.offer(new int[]{n-1, i});\n pacific[0][i] = true;\n atlantic[n-1][i] = true;\n }\n bfs(matrix, pQueue, pacific);\n bfs(matrix, aQueue, atlantic);\n for(int i=0; i<n; i++){\n for(int j=0; j<m; j++){\n if(pacific[i][j] && atlantic[i][j])\n res.add(new int[]{i,j});\n }\n }\n return res;\n }\n public void bfs(int[][]matrix, Queue<int[]> queue, boolean[][]visited){\n int n = matrix.length, m = matrix[0].length;\n while(!queue.isEmpty()){\n int[] cur = queue.poll();\n for(int[] d:dir){\n int x = cur[0]+d[0];\n int y = cur[1]+d[1];\n if(x<0 || x>=n || y<0 || y>=m || visited[x][y] || matrix[x][y] < matrix[cur[0]][cur[1]]){\n continue;\n }\n visited[x][y] = true;\n queue.offer(new int[]{x, y});\n } \n }\n }\n}\n````\nDFS version:\n```\npublic class Solution {\n public List<int[]> pacificAtlantic(int[][] matrix) {\n List<int[]> res = new LinkedList<>();\n if(matrix == null || matrix.length == 0 || matrix[0].length == 0){\n return res;\n }\n int n = matrix.length, m = matrix[0].length;\n boolean[][]pacific = new boolean[n][m];\n boolean[][]atlantic = new boolean[n][m];\n for(int i=0; i<n; i++){\n dfs(matrix, pacific, Integer.MIN_VALUE, i, 0);\n dfs(matrix, atlantic, Integer.MIN_VALUE, i, m-1);\n }\n for(int i=0; i<m; i++){\n dfs(matrix, pacific, Integer.MIN_VALUE, 0, i);\n dfs(matrix, atlantic, Integer.MIN_VALUE, n-1, i);\n }\n for (int i = 0; i < n; i++) \n for (int j = 0; j < m; j++) \n if (pacific[i][j] && atlantic[i][j]) \n res.add(new int[] {i, j});\n return res;\n }\n \n int[][]dir = new int[][]{{0,1},{0,-1},{1,0},{-1,0}};\n \n public void dfs(int[][]matrix, boolean[][]visited, int height, int x, int y){\n int n = matrix.length, m = matrix[0].length;\n if(x<0 || x>=n || y<0 || y>=m || visited[x][y] || matrix[x][y] < height)\n return;\n visited[x][y] = true;\n for(int[]d:dir){\n dfs(matrix, visited, matrix[x][y], x+d[0], y+d[1]);\n }\n }\n}\n````
737
2
[]
71
pacific-atlantic-water-flow
Not understanding the problem. Could someone please explain?
not-understanding-the-problem-could-some-hafj
Hi Guys,\n\nSorry for the noob question. I actually don't understand the problem very well. Where I am not understanding the problem is that, in the matrix give
noobcoder01
NORMAL
2017-02-24T14:38:07.148000+00:00
2018-10-22T08:00:59.082762+00:00
37,647
false
Hi Guys,\n\nSorry for the noob question. I actually don't understand the problem very well. Where I am not understanding the problem is that, in the matrix given in the problem, if the water can flow only in 4 directions, why is it spilling diagonally to 2nd row 3rd column (5)? How is water going from (5) -> (7)? \n\nCould someone please help me understand the problem? \n\nThank you! \n\n```java\nGiven the following 5x5 matrix:\n\n Pacific ~ ~ ~ ~ ~ \n ~ 1 2 2 3 (5) *\n ~ 3 2 3 (4) (4) *\n ~ 2 4 (5) 3 1 *\n ~ (6) (7) 1 4 5 *\n ~ (5) 1 1 2 4 *\n * * * * * Atlantic\n\nReturn:\n\n[[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (positions with parentheses in above matrix).```
518
3
[]
25
pacific-atlantic-water-flow
✅ Short & Easy w/ Explanation & diagrams | Simple Graph traversals - DFS & BFS
short-easy-w-explanation-diagrams-simple-3buh
In a naive approach, we would have to consider each cell and find if it is reachable to both the oceans by checking if it is able to reach - 1. top or left edge
archit91
NORMAL
2021-03-25T12:30:05.499540+00:00
2021-03-25T14:34:13.176855+00:00
34,624
false
In a naive approach, we would have to consider each cell and find if it is reachable to both the oceans by checking if it is able to reach - **1.** top or left edge(atlantic) and, **2.** bottom or right edge (pacific). This would take about **`O((mn)^2)`**, which is not efficient.\n\n***Solution - I (DFS Traversal)***\n\nI will try to explain the process using images provided in LC solution.\n\nWe can observe that there are these cells which can reach -\n\n* None \n* Pacific\n* Atlantic\n* Both Pacific and Atlantic\n\n\nWe need only the cells satisfying the last condition above.\n\n\nNow, if we start from the cells connected to altantic ocean and visit all cells having height greater than current cell (**water can only flow from a cell to another one with height equal or lower**), we are able to reach some subset of cells (let\'s call them **`A`**).\n\n<p align="center">\n<img src="https://assets.leetcode.com/users/images/7fe6657a-4bc1-4d68-8a26-befe6e106371_1616674367.2859244.png" align="center" width="500"/></p>\n\n\n\nNext, we start from the cells connected to pacific ocean and repeat the same process, we find another subset (let\'s call this one **`B`**).\n\n<p align="center"><img src="https://assets.leetcode.com/users/images/ef3a788b-7b66-4c70-a47c-58490b998177_1616674843.2320118.png" align="center" width="500"/></p>\n\n\nThe final answer we get will be the intersection of sets `A` and `B` (**`A \u2229 B`**).\n\n<p align="center"><img src="https://assets.leetcode.com/users/images/6a9f7a1f-105e-4d6c-8e7c-ede3a2f9b6de_1616674967.7329113.png" align="center" width="500"/></p>\n\nSo, we just need to iterate from edge cells, find cells reachable from atlantic (set `A`), cells reachable from pacific (set `B`) and return their intersection. This can be done using DFS or BFS graph traversals.\n\n\n```\nclass Solution {\npublic:\n int m, n;\n\t// denotes cells reachable starting from atlantic and pacific edged cells respectively\n vector<vector<bool> > atlantic, pacific;\n\tvector<vector<int> > ans; \n vector<vector<int> > pacificAtlantic(vector<vector<int>>& mat) {\n if(!size(mat)) return ans;\n m = size(mat), n = size(mat[0]);\n atlantic = pacific = vector<vector<bool> >(m, vector<bool>(n, false));\n\t\t// perform dfs from all edge cells (ocean-connected cells)\n for(int i = 0; i < m; i++) dfs(mat, pacific, i, 0), dfs(mat, atlantic, i, n - 1);\n for(int i = 0; i < n; i++) dfs(mat, pacific, 0, i), dfs(mat, atlantic, m - 1, i); \n return ans;\n }\n void dfs(vector<vector<int> >& mat, vector<vector<bool> >& visited, int i, int j){ \n if(visited[i][j]) return;\n visited[i][j] = true;\n\t\t// if cell reachable from both the oceans, insert into final answer vector\n if(atlantic[i][j] && pacific[i][j]) ans.push_back(vector<int>{i, j}); \n\t\t// dfs from current cell only if height of next cell is greater\n/*\u2B07\uFE0F*/ if(i + 1 < m && mat[i + 1][j] >= mat[i][j]) dfs(mat, visited, i + 1, j); \n/*\u2B06\uFE0F*/ if(i - 1 >= 0 && mat[i - 1][j] >= mat[i][j]) dfs(mat, visited, i - 1, j);\n/*\u27A1\uFE0F*/ if(j + 1 < n && mat[i][j + 1] >= mat[i][j]) dfs(mat, visited, i, j + 1); \n/*\u2B05\uFE0F*/ if(j - 1 >= 0 && mat[i][j - 1] >= mat[i][j]) dfs(mat, visited, i, j - 1);\n }\n};\n```\n\n**Time Complexity :** **`O(M*N)`**, in worst case, all cells are reachable to both oceans and would be visited twice. This case can occur when all elements are equal.\n**Space Complexity :** **`O(M*N)`**, to mark the atlantic and pacific visited cells.\n\n\n---------\n---------\n\n***Solution - II (BFS Traversal)***\n\nBelow is similar solution as above converted to **BFS traversal** -\n\n```\nclass Solution {\npublic:\n int m, n;\n vector<vector<int> > ans;\n vector<vector<bool> > atlantic, pacific;\n queue<pair<int, int> > q;\n vector<vector<int> > pacificAtlantic(vector<vector<int>>& mat) {\n if(!size(mat)) return ans;\n m = size(mat), n = size(mat[0]);\n atlantic = pacific = vector<vector<bool> >(m, vector<bool>(n, false));\n for(int i = 0; i < m; i++) bfs(mat, pacific, i, 0), bfs(mat, atlantic, i, n - 1);\n for(int i = 0; i < n; i++) bfs(mat, pacific, 0, i), bfs(mat, atlantic, m - 1, i); \n return ans;\n }\n void bfs(vector<vector<int> >& mat, vector<vector<bool> >& visited, int i, int j){ \n q.push({i, j});\n while(!q.empty()){\n tie(i, j) = q.front(); q.pop();\n if(visited[i][j]) continue;\n visited[i][j] = true;\n if(atlantic[i][j] && pacific[i][j]) ans.push_back(vector<int>{i, j});\n if(i + 1 < m && mat[i + 1][j] >= mat[i][j]) q.push({i + 1, j});\n if(i - 1 >= 0 && mat[i - 1][j] >= mat[i][j]) q.push({i - 1, j});\n if(j + 1 < n && mat[i][j + 1] >= mat[i][j]) q.push({i, j + 1});\n if(j - 1 >= 0 && mat[i][j - 1] >= mat[i][j]) q.push({i, j - 1});\n }\n }\n};\n```
448
11
['C']
25
pacific-atlantic-water-flow
Python DFS bests 85%. Tips for all DFS in matrix question.
python-dfs-bests-85-tips-for-all-dfs-in-vt2cy
The DFS solution is straightforward. Starting from each point, and dfs its neighbor if the neighbor is equal or less than itself. And maintain two boolean matri
bing28
NORMAL
2016-11-02T21:46:46.729000+00:00
2018-10-18T16:05:51.287201+00:00
59,582
false
The DFS solution is straightforward. Starting from each point, and dfs its neighbor if the neighbor is equal or less than itself. And maintain two boolean matrix for two oceans, indicating an ocean can reach to that point or not. Finally go through all nodes again and see if it can be both reached by two oceans. The trick is if a node is already visited, no need to visited again. Otherwise it will reach the recursion limits.\n\nThis question is very similar to https://leetcode.com/problems/longest-increasing-path-in-a-matrix/ And here are some common tips for this kind of question\n1. init a directions var like `self.directions = [(1,0),(-1,0),(0,1),(0,-1)]` so that when you want to explore from a node, you can just do \n```\nfor direction in self.directions:\n x, y = i + direction[0], j + direction[1]\n```\n\n2. this is a what I normally do for a dfs helper method for exploring a matrix\n```\ndef dfs(self, i, j, matrix, visited, m, n):\n if visited: \n # return or return a value\n for dir in self.directions:\n x, y = i + direction[0], j + direction[1]\n if x < 0 or x >= m or y < 0 or y >= n or matrix[x][y] <= matrix[i][j] (or a condition you want to skip this round):\n continue\n # do something like\n visited[i][j] = True\n # explore the next level like\n self.dfs(x, y, matrix, visited, m, n)\n```\nHope it helps\n\n*Solution*\n```\nclass Solution(object):\n def pacificAtlantic(self, matrix):\n """\n :type matrix: List[List[int]]\n :rtype: List[List[int]]\n """\n if not matrix: return []\n self.directions = [(1,0),(-1,0),(0,1),(0,-1)]\n m = len(matrix)\n n = len(matrix[0])\n p_visited = [[False for _ in range(n)] for _ in range(m)]\n \n a_visited = [[False for _ in range(n)] for _ in range(m)]\n result = []\n \n for i in range(m):\n # p_visited[i][0] = True\n # a_visited[i][n-1] = True\n self.dfs(matrix, i, 0, p_visited, m, n)\n self.dfs(matrix, i, n-1, a_visited, m, n)\n for j in range(n):\n # p_visited[0][j] = True\n # a_visited[m-1][j] = True\n self.dfs(matrix, 0, j, p_visited, m, n)\n self.dfs(matrix, m-1, j, a_visited, m, n)\n \n for i in range(m):\n for j in range(n):\n if p_visited[i][j] and a_visited[i][j]:\n result.append([i,j])\n return result\n \n \n def dfs(self, matrix, i, j, visited, m, n):\n # when dfs called, meaning its caller already verified this point \n visited[i][j] = True\n for dir in self.directions:\n x, y = i + dir[0], j + dir[1]\n if x < 0 or x >= m or y < 0 or y >= n or visited[x][y] or matrix[x][y] < matrix[i][j]:\n continue\n self.dfs(matrix, x, y, visited, m, n)\n# 113 / 113 test cases passed.\n# Runtime: 196 ms\n```\n\n*Solution for longest increasing path in matrix*\n```\nclass Solution(object):\n def longestIncreasingPath(self, matrix):\n """\n :type matrix: List[List[int]]\n :rtype: int\n """\n if not matrix: return 0\n self.directions = [(1,0),(-1,0),(0,1),(0,-1)]\n m = len(matrix)\n n = len(matrix[0])\n cache = [[-1 for _ in range(n)] for _ in range(m)]\n res = 0\n for i in range(m):\n for j in range(n):\n cur_len = self.dfs(i, j, matrix, cache, m, n)\n res = max(res, cur_len)\n return res\n \n def dfs(self, i, j, matrix, cache, m, n):\n if cache[i][j] != -1:\n return cache[i][j]\n res = 1\n for direction in self.directions:\n x, y = i + direction[0], j + direction[1]\n if x < 0 or x >= m or y < 0 or y >= n or matrix[x][y] <= matrix[i][j]:\n continue\n length = 1 + self.dfs(x, y, matrix, cache, m, n)\n res = max(length, res)\n cache[i][j] = res\n return res\n```
393
3
[]
28
pacific-atlantic-water-flow
✅ C++ code | BFS as well as DFS Approach | Simple Solution | Runtime : 20ms
c-code-bfs-as-well-as-dfs-approach-simpl-f4j2
1. DFS Approach :2. BFS Approach :🙂 Also please check out my post on Graphs Algorithms for interviews (All in one) https://leetcode.com/discuss/study-guide/6132
HustlerNitin
NORMAL
2022-02-04T04:54:48.958503+00:00
2025-01-11T17:40:26.547276+00:00
16,566
false
**1. DFS Approach :** ```cpp class Solution { public: vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) { vector<vector<int>> ans; int n = heights.size(); int m = heights[0].size(); vector<vector<bool>> pac(n, vector<bool>(m)); vector<vector<bool>> atl(n, vector<bool>(m)); // we wil start with those cells which were already connected to oceans for (int i = 0; i < n; i++) { dfs(heights, pac, i, 0, -1, -1); // first col dfs(heights, atl, i, m-1, -1, -1); // last col } for (int j = 0; j < m; j++) { dfs(heights, pac, 0, j, -1, -1); // first row dfs(heights, atl, n - 1, j, -1, -1); // last row } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (pac[i][j] && atl[i][j]) ans.push_back({i, j}); } } return ans; } void dfs(vector<vector<int>>& h, vector<vector<bool>>& vis, int i, int j, int oi, int oj) { if (i < 0 || i >= h.size() || j<0 || j>=h[0].size() || vis[i][j]) return; if (oi >= 0 && oj >=0 && h[i][j] < h[oi][oj]) return; // rain water will not move into ocean from smaller to bigger height vis[i][j] = true; dfs(h, vis, i - 1, j, i, j); dfs(h, vis, i + 1, j, i, j); dfs(h, vis, i, j - 1, i, j); dfs(h, vis, i, j + 1, i, j); } }; ``` *** **2. BFS Approach :** ```cpp class Solution { public: void bfs(queue<pair<int,int>> &q, vector<vector<bool>> &vis, vector<vector<int>>& heights, int n, int m) { vector<int>dx = {-1, 0, 1, 0}; vector<int>dy = {0, -1, 0, 1}; while(!q.empty()) { int r = q.front().first; int c = q.front().second; q.pop(); vis[r][c] = true; // mark visited for(int i=0;i<4;i++) { int nr = r + dx[i]; int nc = c + dy[i]; if(nr >=0 && nr < n && nc >=0 && nc < m && heights[r][c] <= heights[nr][nc] && !vis[nr][nc]) { q.push({nr, nc}); } } } } vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) { vector<vector<int>> ans; int n = heights.size(); int m = heights[0].size(); vector<vector<bool>> pac(n, vector<bool>(m)); // visited array vector<vector<bool>> atl(n, vector<bool>(m)); queue<pair<int,int>>q; // push cells connected to pacific ocean for(int i=n-1;i>=0;i--) q.push({i, 0}); // first col for(int i=m-1;i>=0;i--) q.push({0, i}); // first row bfs(q, pac, heights, n, m); // push cells connected to atlantic ocean for(int i=n-1;i>=0;i--) q.push({i, m-1}); // last col for(int i=m-1;i>=0;i--) q.push({n-1, i}); // last row bfs(q, atl, heights, n, m); for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(pac[i][j] && atl[i][j]) ans.push_back({i,j}); } } return ans; } }; ``` 🙂 Also please check out my post on Graphs Algorithms for interviews (All in one) https://leetcode.com/discuss/study-guide/6132428/All-Graph-Algorithms-One-Stop-Destination-Standard-Implementations
169
0
['Depth-First Search', 'Breadth-First Search', 'C', 'C++']
6
pacific-atlantic-water-flow
Python beats 98%. DFS template for Matrix
python-beats-98-dfs-template-for-matrix-q27qu
This is a DFS Template to solve matrix questions:\n\npython\ndef dfs(matrix):\n # 1. Check for an empty graph.\n if not matrix:\n return []\n\n
hxuanhung
NORMAL
2019-11-26T21:23:02.303706+00:00
2020-01-06T10:10:39.686788+00:00
19,356
false
This is a DFS Template to solve matrix questions:\n\n```python\ndef dfs(matrix):\n # 1. Check for an empty graph.\n if not matrix:\n return []\n\n # 2. Initialize\n rows, cols = len(matrix), len(matrix[0])\n visited = set()\n directions = ((0, 1), (0, -1), (1, 0), (-1, 0))\n\n def traverse(i, j):\n # a. Check if visited\n if (i, j) in visited:\n return\n\t\t# b. Else add to visted\n visited.add((i, j))\n\n # c. Traverse neighbors.\n for direction in directions:\n next_i, next_j = i + direction[0], j + direction[1]\n if 0 <= next_i < rows and 0 <= next_j < cols:\n # d. Add in your question-specific checks.\n traverse(next_i, next_j)\n\n # 3. For each point, traverse it.\n for i in range(rows):\n for j in range(cols):\n traverse(i, j)\n\n```\n\nUse this template to addess the problem:\n\n```python\nclass Solution:\n def pacificAtlantic(self, matrix: List[List[int]]) -> List[List[int]]:\n # Check for an empty graph.\n if not matrix:\n return []\n\n p_visited = set()\n a_visited = set()\n rows, cols = len(matrix), len(matrix[0])\n directions = ((0, 1), (0, -1), (1, 0), (-1, 0))\n\n def traverse(i, j, visited):\n if (i, j) in visited:\n return\n visited.add((i, j))\n # Traverse neighbors.\n for direction in directions:\n next_i, next_j = i + direction[0], j + direction[1]\n if 0 <= next_i < rows and 0 <= next_j < cols:\n # Add in your question-specific checks.\n if matrix[next_i][next_j] >= matrix[i][j]:\n traverse(next_i, next_j, visited)\n\n for row in range(rows):\n traverse(row, 0, p_visited)\n traverse(row, cols - 1, a_visited)\n\n for col in range(cols):\n traverse(0, col, p_visited)\n traverse(rows - 1, col, a_visited)\n\n return list(p_visited & a_visited)\n```\n\n> Your runtime beats 98.84 % of python3 submissions\n\n### Complexity Analysis:\n- Time Complexity: since we keep a visited set for each ocean, we only visit a cell if it is not visited before. For each ocean, the worst case is `mn` thus totally `O(mn)`\n\n- Space Complexity: `O(2mn + h) = O(mn)`. \n\t- For each DFS we need `O(h)` space used by the system stack, where `h` is the maximum depth of the recursion. In the worst case, `O(h) = O(m*n)`.\n\t- Each visited set can have at maximum all cells from the matrix so `O(mn)`. Two ocean means `O(2mn)`. \n\n---\n[329. Longest Increasing Path in a Matrix](https://leetcode.com/problems/longest-increasing-path-in-a-matrix/)\n\n**Solution using the above template (LTE):**\n\n```python\nclass Solution:\n def longestIncreasingPath(self, matrix: List[List[int]]) -> int:\n # Check edge case\n if not matrix:\n return 0\n\n # Initialize\n rows, cols = len(matrix), len(matrix[0])\n directions = ((0, 1), (0, -1), (-1, 0), (1, 0))\n visited = set()\n res = 0\n\n def dfs(i, j, visited):\n # Check if visited\n if (i, j) in visited:\n return 0\n\t\t\tvisited.add((i, j))\n res = 1\n\n # work with neighbors\n for direction in directions:\n next_i, next_j = i + direction[0], j + direction[1]\n\n # for each direction we try to find a new count\n direction_count = 0\n if 0 <= next_i < rows and 0 <= next_j < cols:\n if matrix[i][j] < matrix[next_i][next_j]:\n direction_count = 1 + dfs(next_i, next_j, visited)\n\n res = max(direction_count, res)\n\n return res\n\n for row in range(rows):\n for col in range(cols):\n res = max(dfs(row, col, visited), res)\n\n return res\n```\n\nTime Complexity: `O(mn*mn)`\n\n**Template with Memoization**\n\n```python\nclass Solution:\n def longestIncreasingPath(self, matrix: List[List[int]]) -> int:\n # Check edge case\n if not matrix:\n return 0\n\n # Initialize\n rows, cols = len(matrix), len(matrix[0])\n directions = ((0, 1), (0, -1), (-1, 0), (1, 0))\n memo = [[-1] * cols for _ in range(rows)]\n res = 0\n\n def dfs(i, j, visited):\n # Check if visited\n if memo[i][j] != -1:\n return memo[i][j]\n\n res = 1\n\n # work with neighbors\n for direction in directions:\n next_i, next_j = i + direction[0], j + direction[1]\n\n # for each direction we try to find a new count\n direction_count = 0\n if 0 <= next_i < rows and 0 <= next_j < cols:\n if matrix[i][j] < matrix[next_i][next_j]:\n direction_count = 1 + dfs(next_i, next_j, visited)\n\n res = max(direction_count, res)\n\n memo[i][j] = res\n return res\n\n for row in range(rows):\n for col in range(cols):\n res = max(dfs(row, col, memo), res)\n\n return res\n``` \n\n### Complexity Analysis:\n- Time Complexity: `O(mn)` each cell is visited once.\n\n- Space Complexity: `O(mn + h) = O(mn)`. \n\t- For each DFS we need `O(h)` space used by the system stack, where `h` is the maximum depth of the recursion. In the worst case, `O(h) = O(m*n)`.\n\t- Each visited set can have at maximum all cells from the matrix so `O(mn)`\n
146
3
[]
13
pacific-atlantic-water-flow
JAVA || Easy Solution Using DFS || 91% Faster Code
java-easy-solution-using-dfs-91-faster-c-fbt6
\tPLEASE UPVOTE IF YOU LIKE.\n\nclass Solution {\n public List<List<Integer>> pacificAtlantic(int[][] heights) {\n int rows = heights.length, cols = h
shivrastogi
NORMAL
2022-08-31T02:15:26.956915+00:00
2022-08-31T02:15:26.956952+00:00
15,206
false
\tPLEASE UPVOTE IF YOU LIKE.\n```\nclass Solution {\n public List<List<Integer>> pacificAtlantic(int[][] heights) {\n int rows = heights.length, cols = heights[0].length;\n boolean[][] pac = new boolean[rows][cols];\n boolean[][] atl = new boolean[rows][cols];\n \n for (int col = 0; col< cols; col++){\n dfs(0, col, rows, cols, pac, heights[0][col], heights);\n dfs(rows-1, col,rows, cols, atl, heights[rows-1][col], heights);\n }\n for (int row = 0; row<rows; row++){\n dfs(row, 0,rows, cols, pac, heights[row][0], heights);\n dfs(row, cols-1,rows, cols, atl, heights[row][cols-1], heights);\n }\n List<List<Integer>> result = new ArrayList<List<Integer>>();\n for (int i = 0; i < rows; i++)\n for (int j = 0; j < cols; j++){\n if (pac[i][j] && atl[i][j])\n result.add(Arrays.asList(i,j));\n }\n return result;\n }\n private void dfs(int row, int col, int rows, int cols, boolean[][] visited, int prevHeight, int[][] heights){\n if (row < 0 || row >= rows || col < 0 || col >= cols || visited[row][col] || prevHeight > heights[row][col])\n return;\n visited[row][col]= true;\n dfs(row+1, col, rows, cols, visited, heights[row][col], heights);\n dfs(row-1, col, rows, cols, visited, heights[row][col], heights);\n dfs(row, col+1, rows, cols, visited, heights[row][col], heights);\n dfs(row, col-1, rows, cols, visited, heights[row][col], heights);\n \n }\n}\n```
123
0
['Depth-First Search', 'Java']
9
pacific-atlantic-water-flow
Python very concise solution using dfs + set (128ms).
python-very-concise-solution-using-dfs-s-gccs
python\ndef pacificAtlantic(self, matrix: List[List[int]]) -> List[List[int]]:\n if not matrix:\n return []\n p_land = set()\n a_land = set()\n
darktiantian
NORMAL
2019-03-29T12:08:54.561834+00:00
2019-03-29T12:08:54.561898+00:00
9,199
false
```python\ndef pacificAtlantic(self, matrix: List[List[int]]) -> List[List[int]]:\n if not matrix:\n return []\n p_land = set()\n a_land = set()\n R, C = len(matrix), len(matrix[0])\n def spread(i, j, land):\n land.add((i, j))\n for x, y in ((i+1, j), (i, j+1), (i-1, j), (i, j-1)):\n if (0<=x<R and 0<=y<C and matrix[x][y] >= matrix[i][j]\n and (x, y) not in land):\n spread(x, y, land)\n \n for i in range(R):\n spread(i, 0, p_land)\n spread(i, C-1, a_land)\n for j in range(C):\n spread(0, j, p_land)\n spread(R-1, j, a_land)\n return list(p_land & a_land)\n```
119
0
['Depth-First Search', 'Ordered Set', 'Python3']
9
pacific-atlantic-water-flow
Very Concise C++ solution using DFS and bit mask
very-concise-c-solution-using-dfs-and-bi-nqyk
\nclass Solution {\npublic:\n vector<pair<int, int>> res;\n vector<vector<int>> visited;\n void dfs(vector<vector<int>>& matrix, int x, int y, int pre,
zyoppy008
NORMAL
2016-10-09T06:43:09.290000+00:00
2016-10-09T06:43:09.290000+00:00
26,815
false
```\nclass Solution {\npublic:\n vector<pair<int, int>> res;\n vector<vector<int>> visited;\n void dfs(vector<vector<int>>& matrix, int x, int y, int pre, int preval){\n if (x < 0 || x >= matrix.size() || y < 0 || y >= matrix[0].size() \n || matrix[x][y] < pre || (visited[x][y] & preval) == preval) \n return;\n visited[x][y] |= preval;\n if (visited[x][y] == 3) res.push_back({x, y});\n dfs(matrix, x + 1, y, matrix[x][y], visited[x][y]); dfs(matrix, x - 1, y, matrix[x][y], visited[x][y]);\n dfs(matrix, x, y + 1, matrix[x][y], visited[x][y]); dfs(matrix, x, y - 1, matrix[x][y], visited[x][y]);\n }\n\n vector<pair<int, int>> pacificAtlantic(vector<vector<int>>& matrix) {\n if (matrix.empty()) return res;\n int m = matrix.size(), n = matrix[0].size();\n visited.resize(m, vector<int>(n, 0));\n for (int i = 0; i < m; i++) {\n dfs(matrix, i, 0, INT_MIN, 1);\n dfs(matrix, i, n - 1, INT_MIN, 2);\n }\n for (int i = 0; i < n; i++) {\n dfs(matrix, 0, i, INT_MIN, 1);\n dfs(matrix, m - 1, i, INT_MIN, 2);\n }\n return res;\n }\n};\n```
103
6
[]
16
pacific-atlantic-water-flow
[Python] simple bfs, explained
python-simple-bfs-explained-by-dbabichev-dhdx
Let us reverse logic in this problem. Instead of looking for places from which one or another ocean can be reached, we will start from ocean and move in increas
dbabichev
NORMAL
2021-03-25T09:55:45.208103+00:00
2021-03-25T09:55:45.208135+00:00
5,330
false
Let us reverse logic in this problem. Instead of looking for places from which one or another ocean can be reached, we will start from ocean and move in **increasing** way, not decreasing. So, we do the following\n1. Start from `pacific` ocean: all nodes with one of coordinates equal to `0`, and perform `bfs` from all these cells: we put them into queue and then as usual popleft element and add its neigbours if we can: that is we did not visit it yet, and such that new value is more or equal to the old one. In the end my function return all visited cells.\n2. Start from `atlantic` ocean and do exactly the same logic.\n3. Finally, intersect two sets we get on previous two steps and return it (even though it is set, not list, leetcode allows to do it)\n\n**Complexity**: time and space complexity is `O(mn)`: we perform bfs twice and then did intersection of sets.\n\n```\nclass Solution:\n def pacificAtlantic(self, M):\n if not M or not M[0]: return []\n \n m, n = len(M[0]), len(M)\n def bfs(starts):\n queue = deque(starts)\n visited = set(starts)\n while queue:\n x, y = queue.popleft()\n for dx, dy in [(x, y+1), (x, y-1), (x-1, y), (x+1, y)]:\n if 0 <= dx < n and 0 <= dy < m and (dx, dy) not in visited and M[dx][dy] >= M[x][y]:\n queue.append((dx, dy))\n visited.add((dx, dy))\n \n return visited\n \n pacific = [(0, i) for i in range(m)] + [(i, 0) for i in range(1,n)]\n atlantic = [(n-1, i) for i in range(m)] + [(i, m-1) for i in range(n-1)]\n \n return bfs(pacific) & bfs(atlantic)\n```\n\nIf you have any question, feel free to ask. If you like the explanations, please **Upvote!**
101
10
['Breadth-First Search']
7
pacific-atlantic-water-flow
Python solution using bfs and sets.
python-solution-using-bfs-and-sets-by-sh-dw1p
\nclass Solution(object):\n def pacificAtlantic(self, matrix):\n if not matrix: return []\n m, n = len(matrix), len(matrix[0])\n def bfs
sherlock321
NORMAL
2017-03-19T20:12:54.266000+00:00
2018-10-23T07:57:37.042597+00:00
9,881
false
```\nclass Solution(object):\n def pacificAtlantic(self, matrix):\n if not matrix: return []\n m, n = len(matrix), len(matrix[0])\n def bfs(reachable_ocean):\n q = collections.deque(reachable_ocean)\n while q:\n (i, j) = q.popleft()\n for (di, dj) in [(0,1), (0, -1), (1, 0), (-1, 0)]:\n if 0 <= di+i < m and 0 <= dj+j < n and (di+i, dj+j) not in reachable_ocean \\\n and matrix[di+i][dj+j] >= matrix[i][j]:\n q.append( (di+i,dj+j) )\n reachable_ocean.add( (di+i, dj+j) )\n return reachable_ocean \n pacific =set ( [ (i, 0) for i in range(m)] + [(0, j) for j in range(1, n)]) \n atlantic =set ( [ (i, n-1) for i in range(m)] + [(m-1, j) for j in range(n-1)]) \n return list( bfs(pacific) & bfs(atlantic) )\n```
81
0
[]
10
pacific-atlantic-water-flow
C++ DFS
c-dfs-by-raymonm-kfan
```\nclass Solution {\npublic:\n vector> pacificAtlantic(vector>& matrix) {\n vector> r;\n int m = matrix.size();\n if (m == 0)\n
raymonm
NORMAL
2018-02-12T07:34:17.223000+00:00
2018-09-11T13:50:13.315528+00:00
10,335
false
```\nclass Solution {\npublic:\n vector<pair<int, int>> pacificAtlantic(vector<vector<int>>& matrix) {\n vector<pair<int, int>> r;\n int m = matrix.size();\n if (m == 0)\n return r;\n int n = matrix[0].size();\n if (n == 0)\n return r;\n vector<vector<bool>> pacific(m, vector<bool>(n));\n vector<vector<bool>> atlantic(m, vector<bool>(n));\n \n for (int i = 0; i < m; i++) {\n dfs(matrix, pacific, i, 0);\n dfs(matrix, atlantic, i, n-1);\n\n }\n for (int j = 0; j < n; j++) {\n dfs(matrix, pacific, 0, j);\n dfs(matrix, atlantic, m-1, j);\n }\n\n \n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (pacific[i][j] && atlantic[i][j])\n r.push_back(make_pair(i,j));\n }\n }\n return r;\n }\n \n void dfs(vector<vector<int>>& matrix, vector<vector<bool>>& visited, int i, int j) {\n int m = matrix.size();\n int n = matrix[0].size();\n\n visited[i][j] = true;\n //up\n if (i-1 >= 0 && visited[i-1][j] != true && matrix[i-1][j]>=matrix[i][j])\n dfs(matrix, visited, i-1, j);\n //down\n if (i+1 < m && visited[i+1][j] != true && matrix[i+1][j]>=matrix[i][j])\n dfs(matrix, visited, i+1, j);\n //left\n if (j-1 >= 0 && visited[i][j-1] != true && matrix[i][j-1]>=matrix[i][j])\n dfs(matrix, visited, i, j-1);\n //right\n if (j+1 <n && visited[i][j+1] != true && matrix[i][j+1]>=matrix[i][j])\n dfs(matrix, visited, i, j+1);\n\n }\n};
73
0
[]
5
pacific-atlantic-water-flow
🥇 C++ || EXPLAINED || ; ]
c-explained-by-karan_8082-s7c4
UPVOTE IF HELPFuuL\n\nWe need to count the number of cells from which water could flow to both the oceans.\nWater can go to left,top for pacific and to right,do
karan_8082
NORMAL
2022-08-31T01:32:22.730217+00:00
2024-01-19T15:54:15.725837+00:00
10,605
false
**UPVOTE IF HELPFuuL**\n\nWe need to count the number of cells from which water could flow to both the oceans.\nWater can go to **left,top** for pacific and to **right,down** for atlantic.\n\n**APPROACH**\n\nWe just do what is asked for.\n\nWhen at cell ```ht[i][j]``` :\n* we check that water can flow to **left,top** and also to **right,down**.\n* It is similar to finding a path with non-increasing values.\n* To prevent repeation, we use memoization to store the result for certain ```ht[i][j]```.\n\n*How memoization helps :*\n* Let water can flow to both oceans from cell ```ht[i][j]```, so while checking for its adjacent cells, we need not find the complete path to oceans, **we just find a path that leads to a cell that reaches both oceans.**\n\n**Finding water can reach both oceans :**\n* As we going for memoization, we create two ```vector<vector<bool>>``` that stores that whether water can flow to ocean for each ocean respectively.\n* For pacific, we created ```pac``` and water initially water can flow for top and left cells.\n* For atlanic, we created ```atl``` and water initially water can flow for bottom and right cells.\n* Then for each cell, we check whether water flows off :\n* * For cell ```ht[i][j]``` we recurcively call for its adjacent cells, if neightbouring height is less or equal to current cell.\n* * Water can flow off if we reach a cell for which we already have solution.\n* * * For pacific we already made top,left cells ```true``` and same for atlantic.\n\n* Whenever water reaches, make all cells in that path ```true``` so they need not to be calculated in future.\n\n\n\n**UPVOTE IF HELPFuuL**\n\n**C++**\n```\nclass Solution {\npublic:\n int m,n;\n \n bool s(vector<vector<bool>>& ocean, int i, int j, vector<vector<int>>& ht){\n \n if (i<0 || j<0 || i==m || j==n || ht[i][j]==100004) return false;\n if (ocean[i][j]) return true;\n \n int k = ht[i][j];\n ht[i][j]=100004;\n bool zz = false;\n if (i>0 && ht[i-1][j]<=k) zz = zz || s(ocean,i-1,j,ht);\n if (j>0 && ht[i][j-1]<=k) zz = zz || s(ocean,i,j-1,ht);\n if (i<m-1 && ht[i+1][j]<=k) zz = zz || s(ocean,i+1,j,ht);\n if (j<n-1 && ht[i][j+1]<=k) zz = zz || s(ocean,i,j+1,ht);\n \n ocean[i][j]=zz;\n ht[i][j]=k;\n return zz;\n \n }\n \n vector<vector<int>> pacificAtlantic(vector<vector<int>>& ht) {\n m = ht.size();\n n = ht[0].size();\n vector<vector<bool>> pac(m, vector<bool> (n,false));\n vector<vector<bool>> atl(m, vector<bool> (n,false));\n for (int i=0; i<m; i++){\n pac[i][0]=true;\n atl[i][n-1]=true;\n }\n for (int i=0; i<n; i++){\n pac[0][i]=true;\n atl[m-1][i]=true;\n }\n vector<vector<int>> res;\n for (int i=0; i<m; i++){\n for (int j=0; j<n; j++){\n if (s(pac,i,j,ht) && s(atl,i,j,ht)) res.push_back({i,j});\n }\n }return res;\n }\n};\n```\n\n![image](https://assets.leetcode.com/users/images/8cd20a0a-9ab1-456e-a5f3-69f05e67e3ed_1661908619.3639503.jpeg)\n
64
1
['Recursion', 'C', 'C++']
10
pacific-atlantic-water-flow
JS, Python, Java, C++ | Easy DFS / Recursion / DP Solution w/ Explanation
js-python-java-c-easy-dfs-recursion-dp-s-n0x5
(Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful, please upvote this post.)\n\n---\n\n#### Idea:\n
sgallivan
NORMAL
2021-03-25T10:21:58.474967+00:00
2021-03-25T13:01:13.387575+00:00
11,136
false
*(Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful,* ***please upvote*** *this post.)*\n\n---\n\n#### ***Idea:***\n\nIt should be obvious from the start that we\'ll need to solve this problem in reverse. We know that the edges of the input matrix (**M**) will flow water out to the ocean on their respective sides, and we can tell whether an adjacent cell will funnel water to the current cell, so we\'ll have to start from the edges and work our way inward.\n\nUnfortunately, since the path the water will take can possibly wind around, we can\'t do a straight one-time iteration. Instead, we\'ll have to use a **depth first search** (**DFS**) approach with either a **stack**/**queue** structure or **recursion**.\n\nFor each cell that touches an ocean, we\'ll have to follow the reverse path of the water up the continent as far as it will go. Since we only want cells that are reached by both oceans, we\'ll need a data structure to store the preliminary data for the cells while we wait for the opposite ocean to potentially find the same cell.\n\nThere are a few ways we can do this, but I\'ll choose a **dynamic programming** (**DP**) array (**dp**). Since there\'s no real reason to mimic the **2-D matrix** structure of **M**, we can just use a flattened **1-D array** instead, which should save some processing overhead. In order to store both oceans\' data discretely in **dp**, we can use **+1** for one and **+2** for the other. That means that when a cell goes to **3**, it should be added to our answer array (**ans**).\n\nOur DFS recursion function (**dfs**) should also check to make sure that we haven\'t already marked this cell with the current ocean (**w**) by using a **bitwise AND** (**&**) operator. Then, at the end of **dfs** we should fire off new recursions in all four directions, if possible.\n\n---\n\n#### ***Implementation:***\n\nJavascript can use the lighter, typed **Uint8Array** for **dp**.\n\n---\n\n#### ***Javascript Code:***\n\nThe best result for the code below is **100ms / 44.1MB** (beats 100% / 100%).\n```javascript\nvar pacificAtlantic = function(M) {\n if (!M.length) return M\n let y = M.length, x = M[0].length, ans = [],\n dp = new Uint8Array(x * y)\n const dfs = (i, j, w, h) => {\n let ij = i * x + j\n if ((dp[ij] & w) || M[i][j] < h) return\n dp[ij] += w, h = M[i][j]\n if (dp[ij] === 3) ans.push([i,j])\n if (i + 1 < y) dfs(i+1, j, w, h)\n if (i > 0) dfs(i-1, j, w, h)\n if (j + 1 < x) dfs(i, j+1, w, h)\n if (j > 0) dfs(i, j-1, w, h)\n } \n for (let i = 0; i < y; i++) {\n dfs(i, 0, 1, M[i][0])\n dfs(i, x-1, 2, M[i][x-1])\n }\n for (let j = 0; j < x; j++) {\n dfs(0, j, 1, M[0][j])\n dfs(y-1, j, 2, M[y-1][j])\n }\n return ans\n};\n```\n\n---\n\n#### ***Python Code:***\n\nThe best result for the code below is **264ms / 15.6MB** (beats 97% / 53%).\n```python\nclass Solution:\n def pacificAtlantic(self, M: List[List[int]]) -> List[List[int]]:\n if not M: return M\n x, y = len(M[0]), len(M)\n ans, dp = [], [0] * (x * y)\n def dfs(i: int, j: int, w: int, h: int):\n ij = i * x + j\n if dp[ij] & w or M[i][j] < h: return\n dp[ij] += w\n h = M[i][j]\n if dp[ij] == 3: ans.append([i,j])\n if i + 1 < y: dfs(i+1, j, w, h)\n if i > 0: dfs(i-1, j, w, h)\n if j + 1 < x: dfs(i, j+1, w, h)\n if j > 0: dfs(i, j-1, w, h)\n for i in range(y):\n dfs(i, 0, 1, M[i][0])\n dfs(i, x-1, 2, M[i][x-1])\n for j in range(x):\n dfs(0, j, 1, M[0][j])\n dfs(y-1, j, 2, M[y-1][j])\n return ans\n```\n\n---\n\n#### ***Java Code:***\n\nThe best result for the code below is **2ms / 40.4MB** (beats 100% / 43%).\n```java\nclass Solution {\n static void dfs(int i, int j, int w, int h, int[][] M, byte[] dp, List<List<Integer>> ans) {\n int ij = i * M[0].length + j;\n if ((dp[ij] & w) > 0 || M[i][j] < h) return;\n dp[ij] += w;\n h = M[i][j];\n if (dp[ij] == 3) ans.add(Arrays.asList(i,j));\n if (i + 1 < M.length) dfs(i+1, j, w, h, M, dp, ans);\n if (i > 0) dfs(i-1, j, w, h, M, dp, ans);\n if (j + 1 < M[0].length) dfs(i, j+1, w, h, M, dp, ans);\n if (j > 0) dfs(i, j-1, w, h, M, dp, ans);\n }\n public List<List<Integer>> pacificAtlantic(int[][] M) {\n List<List<Integer>> ans = new ArrayList<>();\n if (M.length == 0) return ans;\n int y = M.length, x = M[0].length;\n byte[] dp = new byte[x * y];\n for (int i = 0; i < x; i++) {\n dfs(0, i, 1, M[0][i], M, dp, ans);\n dfs(y-1, i, 2, M[y-1][i], M, dp, ans);\n } \n for (int i = 0; i < y; i++) {\n dfs(i, 0, 1, M[i][0], M, dp, ans);\n dfs(i, x-1, 2, M[i][x-1], M, dp, ans);\n }\n return ans;\n }\n}\n```\n\n---\n\n#### ***C++ Code:***\n\nThe best result for the code below is **24ms / 16.7MB** (beats 100% / 99%).\n```c++\nclass Solution {\npublic:\n vector<vector<int>> pacificAtlantic(vector<vector<int>>& M) {\n vector<vector<int>> ans;\n if (M.empty()) return ans;\n int y = M.size(), x = M[0].size();\n vector<char> dp(y * x);\n for (int i = 0; i < y; i++) {\n dfs(M, dp, i, 0, 1, 0);\n dfs(M, dp, i, x - 1, 2, 0);\n }\n for (int i = 0; i < x; i++) {\n dfs(M, dp, 0, i, 1, 0);\n dfs(M, dp, y - 1, i, 2, 0);\n }\n for (int i = 0; i < y; i++) \n for (int j = 0; j < x; j++) \n if (dp[i * x + j] == 3) \n ans.push_back({i, j});\n return ans;\n }\nprivate:\n void dfs(const vector<vector<int>>& M, vector<char>& dp, int i, int j, int w, int h) {\n int y = M.size(), x = M[0].size(), ij = i * x + j, newh = M[i][j];;\n if ((dp[ij] & w) || M[i][j] < h) return;\n dp[ij] += w;\n if (i + 1 < y) dfs(M, dp, i + 1, j, w, newh);\n if (i > 0) dfs(M, dp, i - 1, j, w, newh);\n if (j + 1 < x) dfs(M, dp, i, j + 1, w, newh);\n if (j > 0) dfs(M, dp, i, j - 1, w, newh);\n }\n};\n```
63
16
['C', 'Python', 'Java', 'JavaScript']
8
pacific-atlantic-water-flow
✅ Pacific Atlantic Water Flow | Short & Easy w/ Explanation & diagrams
pacific-atlantic-water-flow-short-easy-w-1e8v
In a naive approach, we would have to consider each cell and find if it is reachable to both the oceans by checking if it is able to reach - 1. top or left edge
archit91
NORMAL
2021-03-25T12:28:55.738853+00:00
2021-03-25T14:33:58.334629+00:00
3,868
false
In a naive approach, we would have to consider each cell and find if it is reachable to both the oceans by checking if it is able to reach - **1.** top or left edge(atlantic) and, **2.** bottom or right edge (pacific). This would take about **`O((mn)^2)`**, which is not efficient.\n\n***Solution - I (DFS Traversal)***\n\nI will try to explain the process using images provided in LC solution.\n\nWe can observe that there are these cells which can reach -\n\n* None \n* Pacific\n* Atlantic\n* Both Pacific and Atlantic\n\n\nWe need only the cells satisfying the last condition above.\n\n\nNow, if we start from the cells connected to altantic ocean and visit all cells having height greater than current cell (**water can only flow from a cell to another one with height equal or lower**), we are able to reach some subset of cells (let\'s call them **`A`**).\n\n<p align="center">\n<img src="https://assets.leetcode.com/users/images/7fe6657a-4bc1-4d68-8a26-befe6e106371_1616674367.2859244.png" align="center" width="500"/></p>\n\n\n\nNext, we start from the cells connected to pacific ocean and repeat the same process, we find another subset (let\'s call this one **`B`**).\n\n<p align="center"><img src="https://assets.leetcode.com/users/images/ef3a788b-7b66-4c70-a47c-58490b998177_1616674843.2320118.png" align="center" width="500"/></p>\n\n\nThe final answer we get will be the intersection of sets `A` and `B` (**`A \u2229 B`**).\n\n<p align="center"><img src="https://assets.leetcode.com/users/images/6a9f7a1f-105e-4d6c-8e7c-ede3a2f9b6de_1616674967.7329113.png" align="center" width="500"/></p>\n\nSo, we just need to iterate from edge cells, find cells reachable from atlantic (set `A`), cells reachable from pacific (set `B`) and return their intersection. This can be done using DFS or BFS graph traversals.\n\n\n```\nclass Solution {\npublic:\n int m, n;\n\t// denotes cells reachable starting from atlantic and pacific edged cells respectively\n vector<vector<bool> > atlantic, pacific;\n\tvector<vector<int> > ans; \n vector<vector<int> > pacificAtlantic(vector<vector<int>>& mat) {\n if(!size(mat)) return ans;\n m = size(mat), n = size(mat[0]);\n atlantic = pacific = vector<vector<bool> >(m, vector<bool>(n, false));\n\t\t// perform dfs from all edge cells (ocean-connected cells)\n for(int i = 0; i < m; i++) dfs(mat, pacific, i, 0), dfs(mat, atlantic, i, n - 1);\n for(int i = 0; i < n; i++) dfs(mat, pacific, 0, i), dfs(mat, atlantic, m - 1, i); \n return ans;\n }\n void dfs(vector<vector<int> >& mat, vector<vector<bool> >& visited, int i, int j){ \n if(visited[i][j]) return;\n visited[i][j] = true;\n\t\t// if cell reachable from both the oceans, insert into final answer vector\n if(atlantic[i][j] && pacific[i][j]) ans.push_back(vector<int>{i, j}); \n\t\t// dfs from current cell only if height of next cell is greater\n/*\u2B07\uFE0F*/ if(i + 1 < m && mat[i + 1][j] >= mat[i][j]) dfs(mat, visited, i + 1, j); \n/*\u2B06\uFE0F*/ if(i - 1 >= 0 && mat[i - 1][j] >= mat[i][j]) dfs(mat, visited, i - 1, j);\n/*\u27A1\uFE0F*/ if(j + 1 < n && mat[i][j + 1] >= mat[i][j]) dfs(mat, visited, i, j + 1); \n/*\u2B05\uFE0F*/ if(j - 1 >= 0 && mat[i][j - 1] >= mat[i][j]) dfs(mat, visited, i, j - 1);\n }\n};\n```\n\n**Time Complexity :** **`O(M*N)`**, in worst case, all cells are reachable to both oceans and would be visited twice. This case can occur when all elements are equal.\n**Space Complexity :** **`O(M*N)`**, to mark the atlantic and pacific visited cells.\n\n\n---------\n---------\n\n***Solution - II (BFS Traversal)***\n\nBelow is similar solution as above converted to **BFS traversal** -\n\n```\nclass Solution {\npublic:\n int m, n;\n vector<vector<int> > ans;\n vector<vector<bool> > atlantic, pacific;\n queue<pair<int, int> > q;\n vector<vector<int> > pacificAtlantic(vector<vector<int>>& mat) {\n if(!size(mat)) return ans;\n m = size(mat), n = size(mat[0]);\n atlantic = pacific = vector<vector<bool> >(m, vector<bool>(n, false));\n for(int i = 0; i < m; i++) bfs(mat, pacific, i, 0), bfs(mat, atlantic, i, n - 1);\n for(int i = 0; i < n; i++) bfs(mat, pacific, 0, i), bfs(mat, atlantic, m - 1, i); \n return ans;\n }\n void bfs(vector<vector<int> >& mat, vector<vector<bool> >& visited, int i, int j){ \n q.push({i, j});\n while(!q.empty()){\n tie(i, j) = q.front(); q.pop();\n if(visited[i][j]) continue;\n visited[i][j] = true;\n if(atlantic[i][j] && pacific[i][j]) ans.push_back(vector<int>{i, j});\n if(i + 1 < m && mat[i + 1][j] >= mat[i][j]) q.push({i + 1, j});\n if(i - 1 >= 0 && mat[i - 1][j] >= mat[i][j]) q.push({i - 1, j});\n if(j + 1 < n && mat[i][j + 1] >= mat[i][j]) q.push({i, j + 1});\n if(j - 1 >= 0 && mat[i][j - 1] >= mat[i][j]) q.push({i, j - 1});\n }\n }\n};\n```
48
2
['Depth-First Search', 'Breadth-First Search', 'C']
2
pacific-atlantic-water-flow
C++ || Faster than 98% || Simple Code || ✅⭐⭐
c-faster-than-98-simple-code-by-palashhh-mvdp
DO UPVOTE IF IT HELPS !!!!!\n\t\n\t#define vvi vector>\n\t#define vvb vector>\n\t#define vb vector\n\n\tclass Solution {\n\tpublic:\n\t\tint n, m;\n\n\t\t// Go
palashhh
NORMAL
2022-08-31T04:05:14.159714+00:00
2022-08-31T04:32:09.290016+00:00
4,784
false
***DO UPVOTE IF IT HELPS !!!!!***\n\t\n\t#define vvi vector<vector<int>>\n\t#define vvb vector<vector<bool>>\n\t#define vb vector<bool>\n\n\tclass Solution {\n\tpublic:\n\t\tint n, m;\n\n\t\t// Go througout the adjacent if the adjacent\'s height is more or equal to current height\n\t\tvoid dfs(vvi& grid, vvb& flag, int x, int y) {\n\t\t\tflag[x][y] = true;\n\t\t\tif (x - 1 >= 0 && !flag[x - 1][y] && grid[x - 1][y] >= grid[x][y])\n\t\t\t\tdfs(grid, flag, x - 1, y);\n\t\t\tif (x + 1 < n && !flag[x + 1][y] && grid[x + 1][y] >= grid[x][y])\n\t\t\t\tdfs(grid, flag, x + 1, y);\n\t\t\tif (y - 1 >= 0 && !flag[x][y - 1] && grid[x][y - 1] >= grid[x][y])\n\t\t\t\tdfs(grid, flag, x, y - 1);\n\t\t\tif (y + 1 < m && !flag[x][y + 1] && grid[x][y + 1] >= grid[x][y])\n\t\t\t\tdfs(grid, flag, x, y + 1);\n\t\t}\n\n\t\tvvi pacificAtlantic(vvi& heights) {\n\t\t\tn = heights.size();\n\t\t\tm = heights[0].size();\n\n\t\t\tvvb flag1(n, vb(m)), flag2(n, vb(m));\n\t\t\tvvi ans;\n\n\t\t\t// Pacific\n\t\t\t// Do DFS starting from upper border and left border\n\t\t\t// Mark true in flag1 if posibble\n\t\t\tfor (int i = 0; i < n; i++)\n\t\t\t\tdfs(heights, flag1, i, 0);\n\t\t\tfor (int i = 1; i < m; i++)\n\t\t\t\tdfs(heights, flag1, 0, i);\n\n\t\t\t// Attlantic\n\t\t\t// DFS starting from bottom border and right border\n\t\t\t// Mark true in flag2 if posibble\n\t\t\tfor (int i = 0; i < n; i++)\n\t\t\t\tdfs(heights, flag2, i, m - 1);\n\t\t\tfor (int i = 0; i < m - 1; i++)\n\t\t\t\tdfs(heights, flag2, n - 1, i);\n\n\t\t\t// Add cordinate to ans if both flag1 and flag2 is equal to true\n\t\t\tfor (int i = 0; i < n; i++) for (int j = 0; j < m; j++)\n\t\t\t\tif (flag1[i][j] && flag2[i][j])\n\t\t\t\t\tans.push_back({i, j});\n\n\t\t\treturn ans;\n\t\t}\n\t};
39
0
['Depth-First Search', 'Graph', 'C']
9
pacific-atlantic-water-flow
EASY DFS SOLUTION | BEATS 100% SOLUTION | JAVA | PYTHON | C++
easy-dfs-solution-beats-100-solution-jav-1mmu
Upvote if you like quick and simple explanations!\n\nIntuition\nInitially we have the first row/column are able to reach the pacific ocean.\nSay our current loc
AlgoLock
NORMAL
2022-08-31T03:46:58.530732+00:00
2022-08-31T03:51:12.110267+00:00
4,019
false
**Upvote** if you like quick and simple explanations!\n\n**Intuition**\nInitially we have the first row/column are able to reach the pacific ocean.\nSay our current location can reach the pacific, all locations with a height >= the current location can have water flow into our current location and thus reach the pacific.\n\nWe keep this principle and do a DFS over all nodes starting from the ones that can reach the pacific to find all nodes that can reach the pacific ocean if water were placed on it.\nWe do the exact same process for the atlantic ocean and then we check which positions can reach both the atlantic and pacific.\n\n**Note:** for simplicity we can say the sea is at water level (i.e height of 0)\n\n**SOLUTION**\n```java\nclass Solution {\n public List<List<Integer>> pacificAtlantic(int[][] heights) {\n \n int rlen = heights.length;\n int clen = heights[0].length;\n \n List<List<Integer>> output = new ArrayList();\n boolean[][] atlantic = new boolean[rlen][clen];\n boolean[][] pacific = new boolean[rlen][clen];\n\n\t\t//Do a DFS on all nodes at the pacific end and the atlantic end:\n for(int r = 0; r < rlen; r++){\n for(int c = 0; c < clen; c++){ \n if(r == 0 || c == 0){ dfs(pacific, heights, r, c, 0);}\n if(r == rlen-1 || c == clen-1){ dfs(atlantic, heights, r, c, 0); }\n }\n }\n \n\t\t// Check which locations can reach both pacific and atlantic:\n for(int r = 0; r < rlen; r++){\n for(int c = 0; c < clen; c++){ \n if(atlantic[r][c] && pacific[r][c]){\n output.add(Arrays.asList(r,c));\n }\n }\n }\n return output;\n }\n \n // Go to a node - all the larger ones around it can reach the current sea:\n public void dfs(boolean[][] sea, int[][] grid, int r, int c, int prev){\n if(r < 0 || r >= grid.length || c < 0 || c >= grid[0].length) return;\n if(grid[r][c] < prev) return;\n if(sea[r][c]) return; \n \n sea[r][c] = true;\n dfs(sea, grid, r+1, c, grid[r][c]); // bottom \n dfs(sea, grid, r-1, c, grid[r][c]); // top \n dfs(sea, grid, r, c-1, grid[r][c]); // left \n dfs(sea, grid, r, c+1, grid[r][c]); // right\n }\n}\n```\n\nI\'ll be back to making youtube videos on daily leetcode questions, come checkout the youtube channel here: \n**https://www.youtube.com/channel/UCfvW4KQXzpE3ZZqNxAHnaPQ**
36
4
['Depth-First Search', 'Java']
4
pacific-atlantic-water-flow
Simple commented java solution with thinking progress O(n)
simple-commented-java-solution-with-thin-fvi2
```\n/\n1.Naive solution:\n Standard dfs, which means for each point, we check if it can reach both pacific and atlantic, \n for each point, we can possib
donaldtrump
NORMAL
2016-10-09T04:59:40.862000+00:00
2016-10-09T04:59:40.862000+00:00
10,536
false
```\n/*\n1.Naive solution:\n Standard dfs, which means for each point, we check if it can reach both pacific and atlantic, \n for each point, we can possibly check all the rest of points, O(m*n * m*n)\n\n2.A little improvement:\n What about we 4 hash tables, they keep track of all the points we know so far that \n can reach atlantic\n cannot reach atlantic\n can reach pacific\n cannot reach pacific\n It's doable, still hit TLE, although I didn't hit TLE when not submitting the code, but running it using the provided testing environment\n\n3.On the other hand, we can consider the flip side\n We can let the pacific and atlantic ocean "flow into" the matrix as much as possible,\n using 2 boolean arrays, one for each ocean. \n The result are the points that are true in both boolean table\n*/\n\n\npublic class Solution {\n public List<int[]> pacificAtlantic(int[][] matrix) {\n List<int[]> result = new ArrayList<int[]>();\n if(matrix.length == 0 || matrix[0].length == 0) return result; \n boolean[][] pacific = new boolean[matrix.length][matrix[0].length]; // the pacific boolean table\n boolean[][] atlantic = new boolean[matrix.length][matrix[0].length]; // the atlantic booean table\n //initially, all the top and left cells are flooded with pacific water\n //and all the right and bottom cells are flooded with atlantic water\n for(int i = 0; i < matrix.length; i++){\n pacific[i][0] = true;\n atlantic[i][matrix[0].length-1] = true;\n }\n for(int i = 0; i < matrix[0].length; i++){\n pacific[0][i] = true;\n atlantic[matrix.length-1][i] = true; \n }\n //we go around the matrix and try to flood the matrix from 4 side.\n for(int i = 0; i < matrix.length; i++){\n boolean[][] pacificVisited = new boolean[matrix.length][matrix[0].length];\n boolean[][] atlanticVisited = new boolean[matrix.length][matrix[0].length];\n water(pacific, pacificVisited, matrix, i,0);\n water(atlantic, atlanticVisited, matrix, i, matrix[0].length - 1); \n }\n for(int i = 0; i < matrix[0].length; i++){\n boolean[][] pacificVisited = new boolean[matrix.length][matrix[0].length];\n boolean[][] atlanticVisited = new boolean[matrix.length][matrix[0].length];\n water(pacific, pacificVisited, matrix, 0,i);\n water(atlantic, atlanticVisited, matrix, matrix.length - 1, i); \n }\n //check the shared points among 2 tables\n for(int i = 0; i < matrix.length; i++){\n for(int j = 0; j < matrix[0].length; j++){\n if(pacific[i][j] && atlantic[i][j]){\n int[] element = {i,j};\n result.add(element);\n }\n }\n }\n return result;\n }\n //the flood function\n private void water(boolean[][] wet, boolean[][] visited, int[][] matrix, int i , int j){\n wet[i][j] = true;\n visited[i][j] = true;\n int[] x = {0,0,1,-1};\n int[] y = {1,-1,0,0};\n for(int k = 0; k < 4; k++){\n if(i+y[k] >= 0 && i+y[k] < matrix.length && j+x[k] >= 0 && j+x[k] < matrix[0].length \n && !visited[i+y[k]][j+x[k]] && matrix[i+y[k]][j+x[k]] >= matrix[i][j]){\n water(wet, visited, matrix, i+y[k], j+x[k]);\n }\n }\n }\n}````\n\nP.S Sometimes you choose an option just because the alternative is just worse.....
34
9
[]
5
pacific-atlantic-water-flow
Easy understand DFS solution beat 97%
easy-understand-dfs-solution-beat-97-by-44peo
\n\nPython\ndef pacificAtlantic(self, matrix: List[List[int]]) -> List[List[int]]:\n if not matrix or not matrix[0]:return []\n m, n = len(matrix)
jefferyzzy
NORMAL
2020-03-19T03:21:05.988014+00:00
2020-03-19T03:21:05.988069+00:00
6,624
false
![image](https://assets.leetcode.com/users/jefferyzzy/image_1584588025.png)\n\n```Python\ndef pacificAtlantic(self, matrix: List[List[int]]) -> List[List[int]]:\n if not matrix or not matrix[0]:return []\n m, n = len(matrix),len(matrix[0])\n p_visited = set()\n a_visited = set()\n directions = [(-1, 0), (1, 0), (0, 1), (0, -1)]\n def dfs(visited, x,y):\n visited.add((x,y))\n for dx, dy in directions:\n new_x, new_y = x+dx, y+dy\n if 0<=new_x<m and 0<=new_y<n and (new_x,new_y) not in visited and matrix[new_x][new_y]>=matrix[x][y]:\n dfs(visited, new_x,new_y)\n #iterate from left border and right border\n for i in range(m):\n dfs(p_visited,i,0)\n dfs(a_visited,i,n-1)\n #iterate from up border and bottom border\n for j in range(n):\n dfs(p_visited,0,j)\n dfs(a_visited,m-1,j)\n #The intersections of two sets are coordinates where water can flow to both P and A\n return list(p_visited.intersection(a_visited))\n```
33
1
['Ordered Set', 'Python', 'Python3']
4
pacific-atlantic-water-flow
Python DFS Recursion - Simple and Readable
python-dfs-recursion-simple-and-readable-y0ud
Intuition\n\n- Instead of seeing how water can flow from land to the ocean, we can reverse our thinking and see how water can flow from ocean to land\n- Recursi
CompileTimeError
NORMAL
2022-08-31T04:44:34.843329+00:00
2022-08-31T04:44:34.843359+00:00
3,328
false
**Intuition**\n\n- Instead of seeing how water can flow from land to the ocean, we can reverse our thinking and see how water can flow from ocean to land\n- Recursive DFS helps keeps the code clean and readable\n- We try to traverse to a cell that is equal of higher than the previous cell\n- We perform DFS on all four sides, keeping track of coordinates reachable from both Pacific and Atlantic\n- Intersection of two sets of coordinates gives us our answer\n\n**Solution**\n```\nclass Solution:\n def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:\n m, n = len(heights), len(heights[0])\n \n def dfs(i: int, j: int, prev_height: int, coords: Set[Tuple[int]]) -> None:\n if i < 0 or i == m or j < 0 or j == n:\n # out of bounds\n return\n \n if (i, j) in coords:\n # already visited\n return\n \n height = heights[i][j]\n \n if height < prev_height:\n # water can\'t flow to a higher height\n return\n \n # ocean is reachable from current coordinate\n coords.add((i, j))\n \n # all four directions\n dfs(i + 1, j, height, coords)\n dfs(i - 1, j, height, coords)\n dfs(i, j + 1, height, coords)\n dfs(i, j - 1, height, coords)\n \n pacific_coords = set()\n \n # top row\n for j in range(n):\n dfs(0, j, 0, pacific_coords)\n \n # left col\n for i in range(m):\n dfs(i, 0, 0, pacific_coords)\n \n atlantic_coords = set()\n \n # right col\n for i in range(m):\n dfs(i, n - 1, 0, atlantic_coords)\n \n # bottom row\n for j in range(n):\n dfs(m - 1, j, 0, atlantic_coords)\n \n # intersection of coords reachable from both Pacific and Atlantic\n return list(pacific_coords & atlantic_coords)\n```
28
0
['Depth-First Search', 'Recursion', 'Ordered Set', 'Python']
5
pacific-atlantic-water-flow
JAVA 17ms Solution, Simple and Clear, similar to Number of Islands's idea
java-17ms-solution-simple-and-clear-simi-en9v
The idea is as following:\n\nFirst, we can separate Pacific and Atlantic ocean into two, they share the same idea. The only difference is the starting position.
markieff
NORMAL
2016-10-10T19:32:37.182000+00:00
2018-08-16T15:58:48.540118+00:00
10,410
false
The idea is as following:\n\nFirst, we can separate Pacific and Atlantic ocean into two, they share the same idea. The only difference is the starting position.\n\nSecond, we think this problem in the opposite way: all the valid positions must have at least one path to connect to the ocean, so we start from the ocean to find out all the paths.\n\n1, 1, 1, 1\n1, 0, 0, 0\n1, 0, 0, 0\n1, 0, 0, 0\n\nThen we create a new boolean[][] matrix like above, all the beaches is marked as True (1) in the beginning, which means they can connect to the ocean, then we explore from the beach to find out all the paths. The idea is the same for Pacific and Atlantic.\n\nThe last step is to use && to find positions satisfy both Pacific and Atlantic.\n\nHere comes the solution:\n\n\n\n static int[] dx = {-1,0,0,1};\n static int[] dy = {0,1,-1,0};\n public List<int[]> pacificAtlantic(int[][] matrix) {\n List<int[]> res = new ArrayList<>();\n if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return res;\n boolean[][] pacific = new boolean[matrix.length][matrix[0].length];\n boolean[][] atlantic = new boolean[matrix.length][matrix[0].length];\n for (int i = 0; i < matrix.length; i++){\n pacific[i][0] = true;\n atlantic[i][matrix[0].length-1] = true;\n }\n for (int j = 0; j < matrix[0].length; j++){\n pacific[0][j] = true;\n atlantic[matrix.length-1][j] = true;\n }\n for (int i = 0; i < matrix.length; i++){\n explore(pacific, matrix, i, 0);\n explore(atlantic, matrix, i, matrix[0].length-1);\n }\n for (int j = 0; j < matrix[0].length; j++){\n explore(pacific, matrix, 0, j);\n explore(atlantic, matrix, matrix.length-1, j);\n }\n for (int i = 0; i < matrix.length; i++){\n for (int j = 0; j < matrix[0].length; j++){\n if (pacific[i][j] && atlantic[i][j] == true)\n res.add(new int[]{i,j});\n }\n }\n return res;\n \n }\n private void explore(boolean[][] grid, int[][] matrix, int i, int j){\n grid[i][j] = true;\n for (int d = 0; d < dx.length; d++){\n if (i+dy[d] < grid.length && i+dy[d] >= 0 && \n j + dx[d] < grid[0].length && j + dx[d] >= 0 && \n grid[i+dy[d]][j+dx[d]] == false && matrix[i+dy[d]][j+dx[d]] >= matrix[i][j])\n explore(grid, matrix, i+dy[d], j+dx[d]);\n }\n }
27
0
[]
7
pacific-atlantic-water-flow
🥇 PYTHON || EXPLAINED || ; ]
python-explained-by-karan_8082-5f36
UPVOTE IF HELPFuuL\n\nHERE I HAVE CREATED TWO SEPRATE FUNCTION , ONE FUNCTION COULD BE MADE , THIS IS JUST DONE FOR CLARITY.\n\nWe need to count the number of c
karan_8082
NORMAL
2022-08-31T01:38:41.276188+00:00
2022-08-31T01:38:41.276225+00:00
4,967
false
**UPVOTE IF HELPFuuL**\n\n**HERE I HAVE CREATED TWO SEPRATE FUNCTION , ONE FUNCTION COULD BE MADE , THIS IS JUST DONE FOR CLARITY.**\n\nWe need to count the number of cells from which waer could flow to both the oceans.\nWater can go to **left,top** for pacific and to **right,down** for atlantic.\n\n**APPROACH**\n\nWe just do what is asked for.\n\nWhen at cell ```ht[i][j]``` :\n* we check that water can flow to **left,top** and also to **right,down**.\n* It is similar to finding a path with non-increasing values.\n* To prevent repeation, we use memoization to store the result for certain ```ht[i][j]```.\n\n*How memoization helps :*\n* Let water can flow to both oceans from cell ```ht[i][j]```, so while checking for its adjacent cells, we need not find the complete path to oceans, **we just find a path that leads to a cell that reaches both oceans.**\n\n**Finding water can reach both oceans :**\n* As we going for memoization, we create two ```2-D array for atlantic and pacific``` that stores that whether water can flow to ocean for each ocean respectively.\n* For pacific, we created ```pac``` and water initially water can flow for top and left cells.\n* For atlanic, we created ```atl``` and water initially water can flow for bottom and right cells.\n* Then for each cell, we check whether water flows off :\n* * For cell ```ht[i][j]``` we recurcively call for its adjacent cells, if neightbouring height is less or equal to current cell.\n* * Water can flow off if we reach a cell for which we already have solution.\n* * * For pacific we already made top,left cells ```true``` and same for atlantic.\n\n* Whenever water reaches, make all cells in that path ```true``` so they need not to be calculated in future.\n\n\n\n**UPVOTE IF HELPFuuL**\n\n*Here i created and pdated the memoization table first and calculated number of cells afterwards, can be combined to single step.*\n\n**PYTHOON**\n```\nclass Solution:\n def pacificAtlantic(self, ht: List[List[int]]) -> List[List[int]]:\n \n def pac(i,j):\n if rp[i][j]:\n return True\n k=False\n h=ht[i][j]\n ht[i][j]=100001\n if ht[i-1][j]<=h:\n k=k or pac(i-1,j)\n \n if ht[i][j-1]<=h:\n k=k or pac(i,j-1)\n \n if i<m-1 and ht[i+1][j]<=h:\n k=k or pac(i+1,j)\n \n if j<n-1 and ht[i][j+1]<=h:\n k=k or pac(i,j+1)\n \n ht[i][j]=h\n rp[i][j]=k\n return k\n \n def ant(i,j):\n if ra[i][j]:\n return True\n k=False\n h=ht[i][j]\n ht[i][j]=100001\n if i>0 and ht[i-1][j]<=h:\n k=k or ant(i-1,j)\n \n if j>0 and ht[i][j-1]<=h:\n k=k or ant(i,j-1)\n \n if ht[i+1][j]<=h:\n k=k or ant(i+1,j)\n \n if ht[i][j+1]<=h:\n k=k or ant(i,j+1)\n \n ht[i][j]=h\n ra[i][j]=k\n return k\n \n m=len(ht)\n n=len(ht[0])\n rp=[[False for i in range(n)] for j in range(m)]\n ra=[[False for i in range(n)] for j in range(m)]\n \n for i in range(m):\n rp[i][0]=True\n ra[i][-1]=True\n for i in range(n):\n rp[0][i]=True\n ra[-1][i]=True\n \n for i in range(m):\n for j in range(n):\n pac(i,j)\n ant(i,j)\n res=[]\n for i in range(m):\n for j in range(n):\n if rp[i][j] and ra[i][j]:\n res.append([i,j])\n return res\n```\n\n![image](https://assets.leetcode.com/users/images/8cd20a0a-9ab1-456e-a5f3-69f05e67e3ed_1661908619.3639503.jpeg)\n
24
0
['Recursion', 'Python', 'Python3']
1
pacific-atlantic-water-flow
python DFS detailed intuition and explanation
python-dfs-detailed-intuition-and-explan-diel
Intuition\nSome key points:\n1. Water flows downhill or horizontally to cells of equal or lesser height.\n2. We need to find cells that can potentially flow to
clarac
NORMAL
2024-10-31T08:05:41.453413+00:00
2024-10-31T08:06:42.319607+00:00
1,832
false
# Intuition\nSome key points:\n1. Water flows downhill or horizontally to cells of equal or lesser height.\n2. We need to find cells that can potentially flow to both the Pacific (top or left boundary) and Atlantic (bottom or right boundary).\n3. We\'ll use DFS to traverse the matrix, focusing on an efficient boundary-based approach.\n\n## Two DFS methods:\n1. DFS from every cell: Inefficient due to redundant checks and dead ends (meaning that cells are unable to reach any ocean)\n2. Performing DFS on boundary cells.\n - DFS is run \u201Cbackward\u201D from each ocean boundary.\n - Only valid cells that can lead to either the pacific or atlantic ocean will be reached. This is more efficient because we avoid unnecessary searches on cells that lead to dead ends. This means that there might be some cells in the matrix that never get searched (as they cannot be reached from any of the boundaries)\n\n# Approach\n- Perform DFS from cells along each boundary\n\n- We maintain two visited sets - `pacific_visited` and `atlantic_visited` \u2014 to track cells that can reach the Pacific and Atlantic, respectively.\nThese visited sets do not need to be refreshed on each DFS call because once a cell is added to one of these sets, it means that water can flow from that cell to the corresponding ocean, so we don\'t need to revisit it. \n\n- After DFS completes, the intersection of the 2 sets are taken. To get the output format, we convert each cell in the intersection to a list with list comprehension.\n\n- Do refer to the comments in the code to follow through the implementation!\n\n# Complexity\n- Time complexity:\n$O(m*n)$, `m` = number of rows; `n` = number of columns. \nIn the worse case, we will visit each cell once during DFS and all the cells can reach either ocean. \n\n- Space complexity:\n$2(O(m*n)) = O(m*n)$\nSince we used 2 visited sets, in the worse case, each set could contain all the cells of the matrix (assuming each cell can reach both oceans). \nResults stored in the output list would be $O(m*n)$ in the worse case. \n\n# Code\n```python3 []\nclass Solution:\n def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:\n """\n dfs on each boundary cell\n """\n rows = len(heights)\n cols = len(heights[0])\n\n pacific_visited = set()\n atlantic_visited = set()\n \n def dfs(visited, row, col, start_value):\n\n #check grid boundaries\n if row < 0 or row >= rows or col < 0 or col >= cols:\n return\n \n #cell has been visited\n if (row, col) in visited:\n return\n \n #check condition\n if heights[row][col] < start_value:\n return\n \n visited.add((row, col))\n \n #check 4 directions\n dfs(visited, row+1, col, heights[row][col]) \n dfs(visited, row-1, col, heights[row][col])\n dfs(visited, row, col+1, heights[row][col])\n dfs(visited, row, col-1, heights[row][col])\n \n for col in range(cols):\n dfs(pacific_visited, 0, col, heights[0][col]) #top row\n dfs(atlantic_visited, rows-1, col, heights[rows-1][col]) #bottom row\n \n for row in range(rows):\n dfs(pacific_visited, row, 0, heights[row][0]) #1st col\n dfs(atlantic_visited, row, cols-1, heights[row][cols-1]) #bottom row\n \n #find the cells that are in both sets\n output = [list(cell) for cell in pacific_visited & atlantic_visited]\n\n\n return output\n```\nMuch effort was spent in breaking down this problem, so if this helped you, please do give it an upvote as it means alot to me! Do comment if you have any questions or spot a mistake, thank you :)
22
0
['Depth-First Search', 'Matrix', 'Python3']
2
pacific-atlantic-water-flow
C++ || DFS || With Explanation || Easy
c-dfs-with-explanation-easy-by-anubhavsi-eaj9
Start from all the cell connected with pacific ocean and visit all the cell that are greater than or equal to curent cell (since water can flow from adjacent ce
anubhavsingh11
NORMAL
2022-08-31T09:54:09.167943+00:00
2022-08-31T19:11:03.069601+00:00
1,260
false
* Start from all the cell connected with pacific ocean and visit all the cell that are greater than or equal to curent cell **(since water can flow from adjacent cell if height is equal or lower)**\n* **cell connected with pacific** ocean have either **i==0 or j==0**\n* If height is greater or equal means water will be able to reach pacific ocean i.e. this cell is reachable by pacific ocean\n<img src="https://assets.leetcode.com/users/images/8172d3fb-d4c0-42ac-a67c-687c17130bd3_1661938631.9706295.png" alt="drawing" width="500"/>\n* Start from all the cell connected with Atlantic ocean and visit all the cell that are greater than or equal to curent cell **(since water can flow from adjacent cell if height is equal or lower)**\n* **cells connected to atlantic** ocean have either **i==n-1 or j==m-1**\n* If height is greater or equal means water will be able to reach Atlantic ocean i.e. this cell is reachable by Atlantic ocean\n<img src="https://assets.leetcode.com/users/images/4c38fc61-9561-4a23-96d9-5686d3f91635_1661938716.8930888.png" alt="drawing" width="500">\n* Finally include those cells in ans that are reachable from both pacific and atlantic oceans **(means from these cell water can flow in both oceans)**\n<img src="https://assets.leetcode.com/users/images/2f6384b3-5e43-4935-9b08-a968f1ec9e97_1661939112.8621476.png" alt="drawing" width="500">\n\n```\nclass Solution {\npublic:\n void dfs(vector<vector<int>>&heights,vector<vector<int>>&oceans,int i,int j,int n,int m)\n {\n if(i<0 || i>n-1 || j<0 || j>m-1) return;\n if(!oceans[i][j])\n {\n oceans[i][j]=1;\n if(i-1>=0 && heights[i-1][j]>=heights[i][j]) dfs(heights,oceans,i-1,j,n,m);\n if(i+1<n && heights[i+1][j]>=heights[i][j]) dfs(heights,oceans,i+1,j,n,m); \n if(j-1>=0 && heights[i][j-1]>=heights[i][j]) dfs(heights,oceans,i,j-1,n,m);\n if(j+1<m && heights[i][j+1]>=heights[i][j]) dfs(heights,oceans,i,j+1,n,m);\n }\n }\n vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {\n int n=heights.size();\n int m=heights[0].size();\n vector<vector<int>>pacific(n,vector<int>(m,0));\n vector<vector<int>>atlantic(n,vector<int>(m,0));\n vector<vector<int>>ans;\n for(int i=0;i<n;i++)\n {\n for(int j=0;j<m;j++)\n {\n if(i==0 || j==0){\n if(!pacific[i][j])\n {\n dfs(heights,pacific,i,j,n,m);\n }\n }\n }\n }\n \n for(int i=0;i<n;i++)\n {\n for(int j=0;j<m;j++)\n {\n if(i==n-1 || j==m-1){\n if(!atlantic[i][j])\n {\n dfs(heights,atlantic,i,j,n,m);\n }\n }\n }\n }\n for(int i=0;i<n;i++)\n {\n for(int j=0;j<m;j++)\n {\n if(pacific[i][j] && atlantic[i][j])\n ans.push_back({i,j});\n }\n }\n return ans;\n }\n};\n```\n
20
0
['Depth-First Search', 'Graph', 'C']
1
pacific-atlantic-water-flow
Pacific Atlantic Water Flow | JS, Python, Java, C++ | Easy DFS/Recursion/DP Solution w/ Explanation
pacific-atlantic-water-flow-js-python-ja-veb6
(Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful, please upvote this post.)\n\n---\n\n#### Idea:\n
sgallivan
NORMAL
2021-03-25T10:23:11.846757+00:00
2021-03-25T13:01:38.094963+00:00
556
false
*(Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful,* ***please upvote*** *this post.)*\n\n---\n\n#### ***Idea:***\n\nIt should be obvious from the start that we\'ll need to solve this problem in reverse. We know that the edges of the input matrix (**M**) will flow water out to the ocean on their respective sides, and we can tell whether an adjacent cell will funnel water to the current cell, so we\'ll have to start from the edges and work our way inward.\n\nUnfortunately, since the path the water will take can possibly wind around, we can\'t do a straight one-time iteration. Instead, we\'ll have to use a **depth first search** (**DFS**) approach with either a **stack**/**queue** structure or **recursion**.\n\nFor each cell that touches an ocean, we\'ll have to follow the reverse path of the water up the continent as far as it will go. Since we only want cells that are reached by both oceans, we\'ll need a data structure to store the preliminary data for the cells while we wait for the opposite ocean to potentially find the same cell.\n\nThere are a few ways we can do this, but I\'ll choose a **dynamic programming** (**DP**) array (**dp**). Since there\'s no real reason to mimic the **2-D matrix** structure of **M**, we can just use a flattened **1-D array** instead, which should save some processing overhead. In order to store both oceans\' data discretely in **dp**, we can use **+1** for one and **+2** for the other. That means that when a cell goes to **3**, it should be added to our answer array (**ans**).\n\nOur DFS recursion function (**dfs**) should also check to make sure that we haven\'t already marked this cell with the current ocean (**w**) by using a **bitwise AND** (**&**) operator. Then, at the end of **dfs** we should fire off new recursions in all four directions, if possible.\n\n---\n\n#### ***Implementation:***\n\nJavascript can use the lighter, typed **Uint8Array** for **dp**.\n\n---\n\n#### ***Javascript Code:***\n\nThe best result for the code below is **100ms / 44.1MB** (beats 100% / 100%).\n```javascript\nvar pacificAtlantic = function(M) {\n if (!M.length) return M\n let y = M.length, x = M[0].length, ans = [],\n dp = new Uint8Array(x * y)\n const dfs = (i, j, w, h) => {\n let ij = i * x + j\n if ((dp[ij] & w) || M[i][j] < h) return\n dp[ij] += w, h = M[i][j]\n if (dp[ij] === 3) ans.push([i,j])\n if (i + 1 < y) dfs(i+1, j, w, h)\n if (i > 0) dfs(i-1, j, w, h)\n if (j + 1 < x) dfs(i, j+1, w, h)\n if (j > 0) dfs(i, j-1, w, h)\n } \n for (let i = 0; i < y; i++) {\n dfs(i, 0, 1, M[i][0])\n dfs(i, x-1, 2, M[i][x-1])\n }\n for (let j = 0; j < x; j++) {\n dfs(0, j, 1, M[0][j])\n dfs(y-1, j, 2, M[y-1][j])\n }\n return ans\n};\n```\n\n---\n\n#### ***Python Code:***\n\nThe best result for the code below is **264ms / 15.6MB** (beats 97% / 53%).\n```python\nclass Solution:\n def pacificAtlantic(self, M: List[List[int]]) -> List[List[int]]:\n if not M: return M\n x, y = len(M[0]), len(M)\n ans, dp = [], [0] * (x * y)\n def dfs(i: int, j: int, w: int, h: int):\n ij = i * x + j\n if dp[ij] & w or M[i][j] < h: return\n dp[ij] += w\n h = M[i][j]\n if dp[ij] == 3: ans.append([i,j])\n if i + 1 < y: dfs(i+1, j, w, h)\n if i > 0: dfs(i-1, j, w, h)\n if j + 1 < x: dfs(i, j+1, w, h)\n if j > 0: dfs(i, j-1, w, h)\n for i in range(y):\n dfs(i, 0, 1, M[i][0])\n dfs(i, x-1, 2, M[i][x-1])\n for j in range(x):\n dfs(0, j, 1, M[0][j])\n dfs(y-1, j, 2, M[y-1][j])\n return ans\n```\n\n---\n\n#### ***Java Code:***\n\nThe best result for the code below is **2ms / 40.4MB** (beats 100% / 43%).\n```java\nclass Solution {\n static void dfs(int i, int j, int w, int h, int[][] M, byte[] dp, List<List<Integer>> ans) {\n int ij = i * M[0].length + j;\n if ((dp[ij] & w) > 0 || M[i][j] < h) return;\n dp[ij] += w;\n h = M[i][j];\n if (dp[ij] == 3) ans.add(Arrays.asList(i,j));\n if (i + 1 < M.length) dfs(i+1, j, w, h, M, dp, ans);\n if (i > 0) dfs(i-1, j, w, h, M, dp, ans);\n if (j + 1 < M[0].length) dfs(i, j+1, w, h, M, dp, ans);\n if (j > 0) dfs(i, j-1, w, h, M, dp, ans);\n }\n public List<List<Integer>> pacificAtlantic(int[][] M) {\n List<List<Integer>> ans = new ArrayList<>();\n if (M.length == 0) return ans;\n int y = M.length, x = M[0].length;\n byte[] dp = new byte[x * y];\n for (int i = 0; i < x; i++) {\n dfs(0, i, 1, M[0][i], M, dp, ans);\n dfs(y-1, i, 2, M[y-1][i], M, dp, ans);\n } \n for (int i = 0; i < y; i++) {\n dfs(i, 0, 1, M[i][0], M, dp, ans);\n dfs(i, x-1, 2, M[i][x-1], M, dp, ans);\n }\n return ans;\n }\n}\n```\n\n---\n\n#### ***C++ Code:***\n\nThe best result for the code below is **24ms / 16.7MB** (beats 100% / 99%).\n```c++\nclass Solution {\npublic:\n vector<vector<int>> pacificAtlantic(vector<vector<int>>& M) {\n vector<vector<int>> ans;\n if (M.empty()) return ans;\n int y = M.size(), x = M[0].size();\n vector<char> dp(y * x);\n for (int i = 0; i < y; i++) {\n dfs(M, dp, i, 0, 1, 0);\n dfs(M, dp, i, x - 1, 2, 0);\n }\n for (int i = 0; i < x; i++) {\n dfs(M, dp, 0, i, 1, 0);\n dfs(M, dp, y - 1, i, 2, 0);\n }\n for (int i = 0; i < y; i++) \n for (int j = 0; j < x; j++) \n if (dp[i * x + j] == 3) \n ans.push_back({i, j});\n return ans;\n }\nprivate:\n void dfs(const vector<vector<int>>& M, vector<char>& dp, int i, int j, int w, int h) {\n int y = M.size(), x = M[0].size(), ij = i * x + j, newh = M[i][j];;\n if ((dp[ij] & w) || M[i][j] < h) return;\n dp[ij] += w;\n if (i + 1 < y) dfs(M, dp, i + 1, j, w, newh);\n if (i > 0) dfs(M, dp, i - 1, j, w, newh);\n if (j + 1 < x) dfs(M, dp, i, j + 1, w, newh);\n if (j > 0) dfs(M, dp, i, j - 1, w, newh);\n }\n};\n```
19
8
[]
0
pacific-atlantic-water-flow
Easy to Read Java DFS Flood From Ocean
easy-to-read-java-dfs-flood-from-ocean-b-eqal
Top answer right now uses 2 matrices to track visited but we can do it with one - use codes for visited by Pacific, Atlantic, or both.\n\n\nclass Solution {\n
zhaosteven
NORMAL
2019-06-22T19:16:17.510565+00:00
2019-06-22T19:16:17.510635+00:00
2,961
false
Top answer right now uses 2 matrices to track visited but we can do it with one - use codes for visited by Pacific, Atlantic, or both.\n\n```\nclass Solution {\n public List<List<Integer>> pacificAtlantic(int[][] matrix) {\n List<List<Integer>> res = new ArrayList();\n if (matrix.length == 0 || matrix[0].length == 0) return res;\n // visited by pacific == -1, atlantic == -2, both == -3\n int[][] visited = new int[matrix.length][matrix[0].length];\n for (int i = 0; i < matrix.length; i++) {\n dfs(matrix, visited, i, 0, -1);\n dfs(matrix, visited, i, matrix[0].length-1, -2);\n }\n for (int i = 0; i < matrix[0].length; i++) {\n dfs(matrix, visited, 0, i, -1);\n dfs(matrix, visited, matrix.length-1, i, -2);\n }\n \n \n for (int y = 0; y < matrix.length; y++) {\n for (int x = 0; x < matrix[0].length; x++) {\n if (visited[y][x] == -3) {\n res.add(Arrays.asList(y,x));\n }\n }\n }\n return res;\n }\n \n private void dfs(int[][] matrix, int[][] visited, int y, int x, int code) {\n int val = matrix[y][x];\n int vis = visited[y][x];\n if (vis == code || vis == -3) return;\n visited[y][x] = vis < 0 ? -3 : code;\n \n boolean left = x > 0 && matrix[y][x-1] >= val;\n boolean right = x < matrix[0].length -1 && matrix[y][x+1] >= val;\n boolean up = y > 0 && matrix[y-1][x] >= val;\n boolean down = y < matrix.length - 1 && matrix[y+1][x] >= val;\n \n if (left) dfs(matrix, visited, y, x-1, code);\n if (right) dfs(matrix, visited, y, x+1, code);\n if (up) dfs(matrix, visited, y-1, x, code);\n if (down) dfs(matrix, visited, y+1, x, code);\n }\n}\n```
19
0
[]
6
pacific-atlantic-water-flow
Python 3 | BFS, Set Intersection | Explanation
python-3-bfs-set-intersection-explanatio-jhop
Explanation\n- Starting from pacific and atlantic, going back to the water, check which position they can reach\n\t- Of course, following statement should be re
idontknoooo
NORMAL
2020-10-06T21:24:13.580725+00:00
2020-10-06T21:24:13.580773+00:00
2,850
false
### Explanation\n- Starting from pacific and atlantic, going back to the water, check which position they can reach\n\t- Of course, following statement should be reversed\n\t- > Water can only flow in four directions (up, down, left, or right) from a cell to another one with height equal or lower.\n\t- i.e. Pacific or Atlantic water can only go to water, which height is equal or higher\n- Take intersection of 2 sets to find common positions\n### Implementation\n```\nclass Solution:\n def pacificAtlantic(self, matrix: List[List[int]]) -> List[List[int]]:\n if not matrix: return []\n m, n = len(matrix), len(matrix[0])\n pacific = [(0, i) for i in range(n)] + [(i, 0) for i in range(1, m)]\n atlantic = [(m-1, i) for i in range(n)] + [(i, n-1) for i in range(m-1)]\n def bfs(q):\n visited = set()\n q = collections.deque(q)\n while q:\n i, j = q.popleft()\n visited.add((i, j))\n for ii, jj in map(lambda x: (x[0]+i, x[1]+j), [(-1, 0), (1, 0), (0, -1), (0, 1)]):\n if 0 <= ii < m and 0 <= jj < n and (ii, jj) not in visited and matrix[ii][jj] >= matrix[i][j]:\n q.append((ii, jj))\n return visited \n return bfs(pacific) & bfs(atlantic)\n```
18
1
['Breadth-First Search', 'Ordered Set', 'Python', 'Python3']
4
pacific-atlantic-water-flow
[Java] BFS Easy to Understand | Let water flow from respective occean sides
java-bfs-easy-to-understand-let-water-fl-e1d5
\nclass Solution {\n public List<List<Integer>> pacificAtlantic(int[][] matrix) {\n if(matrix.length == 0)\n return new ArrayList();\n
i18n
NORMAL
2021-03-25T17:16:56.550519+00:00
2021-03-25T17:16:56.550557+00:00
372
false
```\nclass Solution {\n public List<List<Integer>> pacificAtlantic(int[][] matrix) {\n if(matrix.length == 0)\n return new ArrayList();\n \n int R = matrix.length, C = matrix[0].length;\n \n boolean[][] pacific = new boolean[R][C];\n boolean[][] atlantic = new boolean[R][C];\n \n for(int i = 0; i < R; i++) {\n bfs(i, 0, matrix, pacific);\n bfs(i, C - 1, matrix, atlantic);\n }\n \n for(int j = 0; j < C; j++) {\n bfs(0, j, matrix, pacific);\n bfs(R - 1, j, matrix, atlantic);\n }\n \n List<List<Integer>> list = new ArrayList();\n for(int i = 0; i < R; i++) {\n for(int j = 0; j < C; j++) {\n if(pacific[i][j] && atlantic[i][j]) {\n list.add(Arrays.asList(i, j));\n }\n }\n }\n \n return list;\n }\n \n private void bfs(int x, int y, int[][] matrix, boolean[][] visited) {\n int R = matrix.length, C = matrix[0].length;\n Queue<int[]> q = new LinkedList<>();\n q.add(new int[]{x, y});\n visited[x][y] = true;\n int[][] dir = new int[][] {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};\n while(q.size() > 0) {\n x = q.peek()[0];\n y = q.peek()[1];\n q.poll();\n \n for(int[] d : dir) {\n int nx = x + d[0];\n int ny = y + d[1];\n \n if(nx >= 0 && nx < R && ny >= 0 && ny < C && matrix[x][y] <= matrix[nx][ny] && !visited[nx][ny]) {\n q.add(new int[]{nx, ny});\n visited[nx][ny] = true;\n }\n }\n }\n }\n}\n```
16
7
[]
1
pacific-atlantic-water-flow
Easy BFS Solution | C++| Time(N*M) | Space(N*M)
easy-bfs-solution-c-timenm-spacenm-by-nx-e28p
\nclass Solution {\npublic:\n vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {\n \n\t\tqueue<pair<int,int>>q;\n\tset<vector<int>>an
nxmxn
NORMAL
2022-08-31T09:36:34.182738+00:00
2022-08-31T09:46:05.640033+00:00
1,180
false
```\nclass Solution {\npublic:\n vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {\n \n\t\tqueue<pair<int,int>>q;\n\tset<vector<int>>ans;\n\tmap<pair<int,int>,bool>atlantic,pacific;\n\n\tfor(int count=0;count<heights[0].size();++count)\n\t\tatlantic[{0,count}]=true,q.push({0,count});\n\n\t\tfor(int count =0;count<heights.size();++count)\n\t\t\t\tatlantic[{count,0}]=true,q.push({count,0});\n\n\n\tint dir[4][2]={{0,1},{1,0},{-1,0},{0,-1}};\n\n\twhile(!q.empty())\n\t{\n\t\tint x = q.front().first;\n\t\tint y = q.front().second;\n\n\t\tfor(int count =0;count<4;++count)\n\t\t{\n\t\t\tint i = x+dir[count][0];\n\t\t\tint j = y+dir[count][1];\n\n\t\t\tif(i>=0 && j>=0 && i<heights.size() && j<heights[0].size() && !atlantic[{i,j}] && heights[i][j]>=heights[x][y])\n\t\t\t{\n\t\t\t\tatlantic[{i,j}]=1;\n\t\t\t\tq.push({i,j});\n\t\t\t}\n\t\t}\n\t\tq.pop();\n\t}\n\n\t for(int count=0;count<heights[0].size();++count)\n\t\tpacific[{heights.size()-1,count}]=true,q.push({heights.size()-1,count});\n\n\t for(int count=0;count<heights.size();++count)\n\t pacific[{count,heights[0].size()-1}]=true,q.push({count,heights[0].size()-1});\n\n\n\t while(!q.empty())\n\t{\n\t\tint x = q.front().first;\n\t\tint y = q.front().second;\n\t\tif(atlantic[{x,y}])\n\t\t\tans.insert({x,y});\n\t\tfor(int count =0;count<4;++count)\n\t\t{\n\t\t\tint i = x+dir[count][0];\n\t\t\tint j = y+dir[count][1];\n\n\t\t\tif(i>=0 && j>=0 && i<heights.size() && j<heights[0].size() && !pacific[{i,j}] && heights[i][j]>=heights[x][y])\n\t\t\t{\n\n\n\t\t\t\tpacific[{i,j}]=1;\n\t\t\t\tq.push({i,j});\n\t\t\t}\n\t\t}\n\t\tq.pop();\n\t}\n\n\treturn {ans.begin(),ans.end()};\n} \n\n};\n```
15
0
[]
14
pacific-atlantic-water-flow
Python Elegant & Short | DFS | 99.21% faster
python-elegant-short-dfs-9921-faster-by-qpaop
\n\n\nclass Solution:\n\t"""\n\tTime: O(n*m)\n\tMemory: O(n*m)\n\t"""\n\n\tMOVES = [(-1, 0), (0, -1), (1, 0), (0, 1)]\n\n\tdef pacificAtlantic(self, heights:
Kyrylo-Ktl
NORMAL
2022-08-31T09:02:03.211299+00:00
2022-09-30T13:23:39.574262+00:00
2,806
false
![image](https://assets.leetcode.com/users/images/6e32f2ac-4bce-4a83-aa85-26bc06457eeb_1661969728.801651.png)\n\n```\nclass Solution:\n\t"""\n\tTime: O(n*m)\n\tMemory: O(n*m)\n\t"""\n\n\tMOVES = [(-1, 0), (0, -1), (1, 0), (0, 1)]\n\n\tdef pacificAtlantic(self, heights: List[List[int]]) -> Set[Tuple[int, int]]:\n\t\tdef dfs(i: int, j: int, visited: set):\n\t\t\tvisited.add((i, j))\n\t\t\tfor di, dj in self.MOVES:\n\t\t\t\tx, y = i + di, j + dj\n\t\t\t\tif 0 <= x < n and 0 <= y < m and (x, y) not in visited and heights[i][j] <= heights[x][y]:\n\t\t\t\t\tdfs(x, y, visited)\n\n\t\tn, m = len(heights), len(heights[0])\n\n\t\tatl_visited = set()\n\t\tpas_visited = set()\n\n\t\tfor i in range(n):\n\t\t\tdfs(i, 0, pas_visited)\n\t\t\tdfs(i, m - 1, atl_visited)\n\n\t\tfor j in range(m):\n\t\t\tdfs( 0, j, pas_visited)\n\t\t\tdfs(n - 1, j, atl_visited)\n\n\t\treturn atl_visited & pas_visited\n```\n\nIf you like this solution remember to **upvote it** to let me know.
15
0
['Depth-First Search', 'Python', 'Python3']
3
pacific-atlantic-water-flow
Java Easy Solution
java-easy-solution-by-arpitsingal6098-6lnr
Upvote if you like the solution\n```\nclass Solution {\n static int[][] dir={{0,1},{0,-1},{1,0},{-1,0}};\n public List> pacificAtlantic(int[][] heights) {
arpitsingal6098
NORMAL
2021-07-19T18:08:54.366772+00:00
2021-07-21T17:52:39.732526+00:00
1,855
false
Upvote if you like the solution\n```\nclass Solution {\n static int[][] dir={{0,1},{0,-1},{1,0},{-1,0}};\n public List<List<Integer>> pacificAtlantic(int[][] heights) {\n List<List<Integer>> ans=new ArrayList<>();\n int m=heights.length;\n int n=heights[0].length;\n boolean[][] pac=new boolean[heights.length][heights[0].length];\n boolean[][] atl=new boolean[heights.length][heights[0].length];\n \n for(int i=0;i<n;i++){\n dfs(heights,0,i,Integer.MIN_VALUE,pac);\n dfs(heights,m-1,i,Integer.MIN_VALUE,atl);\n }\n for(int j=0;j<m;j++){\n dfs(heights,j,0,Integer.MIN_VALUE,pac);\n dfs(heights,j,n-1,Integer.MIN_VALUE,atl);\n }\n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++){\n if(pac[i][j] && atl[i][j]){\n List<Integer> l=new ArrayList<>();\n l.add(i);\n l.add(j);\n ans.add(l);\n }\n }\n }\n return ans;\n }\n public static void dfs(int[][] heights,int i, int j,int prev, boolean[][] arr){\n if(i<0 || j<0 || i>=heights.length || j>=heights[0].length || arr[i][j]==true || heights[i][j]<prev)return;\n \n arr[i][j]=true;\n for(int k=0;k<4;k++){\n int x=i+dir[k][0];\n int y=j+dir[k][1];\n \n dfs(heights,x,y,heights[i][j],arr);\n }\n \n \n }\n}
15
0
['Java']
0
pacific-atlantic-water-flow
Explanation + dfs
explanation-dfs-by-11grossmane-jftz
\n/**\n * @param {number[][]} matrix\n * @return {number[][]}\n */\n\n/*\n\nbasic idea -->\npopulate cells reached from atlantic and cells reached from pacific
11grossmane
NORMAL
2021-01-15T17:36:54.399493+00:00
2021-01-15T17:36:54.399527+00:00
2,749
false
```\n/**\n * @param {number[][]} matrix\n * @return {number[][]}\n */\n\n/*\n\nbasic idea -->\npopulate cells reached from atlantic and cells reached from pacific with dfs\nloop through matrix\nadd coords to return array if they exist in both the atlantic matrix and the pacific matrix\nreturn result\n\ndfs --> \n1. base - return if out of bounds\n2. base - return if our previous spot was larger because we are only marking spot as true\nif it is larger than prev (prev) **this is tricky, we aren\'t checking if the water is\nable to flow to this spot from a previous spot...instead we are checking if water can flow out FROM this spot\nTO the "prev" spot, so really prev is kind of a confusing name, because it represents the next spot that water could flow to\n2. base - if the spot is already marked as true we can just return, because it means that water from this spot can already reach ocean\n3. if we\'ve reached this point it means that our flow has not yet been interrupted from our starting point\nso we CAN reach our ocean (pacific or atlantic) from the current spot, so we simply mark that in our ocean i.e. ocean[i][j] = true\n4. call dfs recursively on all 4 surrounding spots\n\n\n*/\nvar pacificAtlantic = function(matrix) {\n if (matrix.length === 0) return [] \n let numRows = matrix.length\n let numCols = matrix[0].length\n \n let atlantic = []\n let pacific = []\n for (let i = 0;i<numRows;i++){\n atlantic.push(new Array(numCols).fill(false))\n pacific.push(new Array(numCols).fill(false))\n }\n \n for (let col=0 ;col<matrix[0].length;col++){\n dfs(matrix, 0, col, Number.MIN_SAFE_INTEGER, pacific)\n dfs(matrix, numRows - 1, col, Number.MIN_SAFE_INTEGER, atlantic)\n }\n \n for (let row = 0;row<matrix.length; row++){\n dfs(matrix, row, 0, Number.MIN_SAFE_INTEGER, pacific)\n dfs(matrix, row, numCols - 1, Number.MIN_SAFE_INTEGER, atlantic)\n }\n \n let res = []\n for (let i=0;i<numRows;i++){\n for (let j=0;j<numCols;j++){\n if (atlantic[i][j] && pacific[i][j]){\n res.push([i, j])\n }\n }\n }\n return res\n}\n \n\n\nconst dfs = (matrix, i, j, prev, ocean) =>{\n //checkOutOfBounds\n if (i<0 ||\n i > matrix.length -1 ||\n j < 0 ||\n j > matrix[i].length - 1\n ) return\n \n \n if (matrix[i][j] < prev) return\n if (ocean[i][j]) return\n ocean[i][j] = true\n \n dfs(matrix, i+1, j, matrix[i][j], ocean)\n dfs(matrix, i-1, j, matrix[i][j], ocean)\n dfs(matrix, i, j+1, matrix[i][j], ocean)\n dfs(matrix, i, j-1, matrix[i][j], ocean) \n}\n\n\n```
15
0
['Depth-First Search', 'JavaScript']
4
pacific-atlantic-water-flow
Easy to understand C++ Solution, DFS, beats 93%
easy-to-understand-c-solution-dfs-beats-2glbm
Runtime: 44 ms, faster than 93.45% of C++ online submissions for Pacific Atlantic Water Flow.\nMemory Usage: 14.1 MB, less than 100.00% of C++ online submission
pooja0406
NORMAL
2019-11-29T14:45:30.755044+00:00
2019-11-29T14:45:30.755075+00:00
1,107
false
Runtime: 44 ms, faster than 93.45% of C++ online submissions for Pacific Atlantic Water Flow.\nMemory Usage: 14.1 MB, less than 100.00% of C++ online submissions for Pacific Atlantic Water Flow.\n\n```\nclass Solution {\npublic:\n vector<vector<int>> pacificAtlantic(vector<vector<int>>& matrix) {\n \n int n = matrix.size();\n if(n == 0) return {};\n int m = matrix[0].size();\n \n vector<vector<int>> res;\n vector<vector<bool>> pacafic(n, vector<bool>(m, false));\n vector<vector<bool>> atlantic(n, vector<bool>(m, false));\n \n for(int i=0; i<m; i++)\n {\n dfs(matrix, pacafic, INT_MIN, 0, i);\n dfs(matrix, atlantic, INT_MIN, n-1, i);\n }\n \n for(int i=0; i<n; i++)\n {\n dfs(matrix, pacafic, INT_MIN, i, 0);\n dfs(matrix, atlantic, INT_MIN, i, m-1);\n }\n \n for(int i=0; i<n; i++)\n {\n for(int j=0; j<m; j++)\n {\n if(pacafic[i][j] && atlantic[i][j])\n res.push_back(vector<int> {i,j});\n }\n }\n \n return res;\n }\n \n void dfs(vector<vector<int>>& matrix, vector<vector<bool>>& visited, int prev, int i, int j)\n {\n if(i < 0 || j < 0 || i >= matrix.size() || j >= matrix[0].size() || prev > matrix[i][j] || visited[i][j]) return;\n \n visited[i][j] = true;\n dfs(matrix, visited, matrix[i][j], i+1, j);\n dfs(matrix, visited, matrix[i][j], i-1, j);\n dfs(matrix, visited, matrix[i][j], i, j+1);\n dfs(matrix, visited, matrix[i][j], i, j-1);\n }\n};\n
15
0
['Depth-First Search']
0
pacific-atlantic-water-flow
417: Time 96.50% and Space 94.12%, Solution with step by step explanation
417-time-9650-and-space-9412-solution-wi-1qca
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n1. Check if the input matrix is empty. If it is, return an empty list.\n\
Marlen09
NORMAL
2023-03-07T02:54:47.658209+00:00
2023-03-07T02:54:47.658243+00:00
4,155
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Check if the input matrix is empty. If it is, return an empty list.\n\n2. Determine the number of rows and columns in the input matrix.\n\n3. Create two visited matrices of the same size as the input matrix, one for each ocean.\n\n4. Create two empty queues, one for each ocean.\n\n5. Add all the cells in the first and last rows to the Pacific queue, and mark them as visited in the Pacific visited matrix. Add all the cells in the first and last columns to the Atlantic queue, and mark them as visited in the Atlantic visited matrix.\n\n6. Define a helper function, bfs, that takes a queue and a visited matrix as input, and runs a breadth-first search on the input matrix starting from the cells in the queue. The function visits each cell that can flow to the ocean and adds it to the queue.\n\n7. Run bfs on both oceans, starting from the boundary cells.\n\n8. Find the cells that can flow to both oceans by iterating through all cells in the input matrix, and adding the ones that are marked as visited in both the Pacific and Atlantic visited matrices to the result list.\n\n9. Return the result list.\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 pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:\n if not heights:\n return []\n \n rows, cols = len(heights), len(heights[0])\n \n # Create visited matrices for both oceans\n pacific_visited = [[False] * cols for _ in range(rows)]\n atlantic_visited = [[False] * cols for _ in range(rows)]\n \n # Create queue for both oceans\n pacific_queue = deque()\n atlantic_queue = deque()\n \n # Add cells in the first and last rows to their respective queues\n for col in range(cols):\n pacific_queue.append((0, col))\n atlantic_queue.append((rows-1, col))\n pacific_visited[0][col] = True\n atlantic_visited[rows-1][col] = True\n \n # Add cells in the first and last columns to their respective queues\n for row in range(rows):\n pacific_queue.append((row, 0))\n atlantic_queue.append((row, cols-1))\n pacific_visited[row][0] = True\n atlantic_visited[row][cols-1] = True\n \n # Define helper function to check if a cell can flow to an ocean\n def bfs(queue, visited):\n while queue:\n row, col = queue.popleft()\n # Check adjacent cells\n for dr, dc in [(0, 1), (0, -1), (1, 0), (-1, 0)]:\n r, c = row + dr, col + dc\n # Check if cell is within bounds and hasn\'t been visited yet\n if 0 <= r < rows and 0 <= c < cols and not visited[r][c]:\n # Check if cell can flow to the ocean\n if heights[r][c] >= heights[row][col]:\n visited[r][c] = True\n queue.append((r, c))\n \n # Run BFS on both oceans starting from the boundary cells\n bfs(pacific_queue, pacific_visited)\n bfs(atlantic_queue, atlantic_visited)\n \n # Find the cells that can flow to both oceans\n result = []\n for row in range(rows):\n for col in range(cols):\n if pacific_visited[row][col] and atlantic_visited[row][col]:\n result.append([row, col])\n \n return result\n\n```
14
0
['Array', 'Depth-First Search', 'Breadth-First Search', 'Python', 'Python3']
0
pacific-atlantic-water-flow
My Java Solution using DFS
my-java-solution-using-dfs-by-vrohith-e2rl
\nclass Solution {\n public List<List<Integer>> pacificAtlantic(int[][] matrix) {\n List<List<Integer>> result = new ArrayList<>();\n int row =
vrohith
NORMAL
2021-03-25T09:38:22.070705+00:00
2021-03-25T09:38:22.070733+00:00
1,385
false
```\nclass Solution {\n public List<List<Integer>> pacificAtlantic(int[][] matrix) {\n List<List<Integer>> result = new ArrayList<>();\n int row = matrix.length;\n if (row == 0)\n return result;\n int col = matrix[0].length;\n boolean [][] pacific = new boolean [row][col];\n boolean [][] atlantic = new boolean [row][col];\n // top bottom\n for (int i=0; i<col; i++) {\n dfs(matrix, 0, i, matrix[0][i], pacific);\n dfs(matrix, row-1, i, matrix[row-1][i], atlantic);\n }\n // left right\n for (int i=0; i<row; i++) {\n dfs(matrix, i, 0, matrix[i][0], pacific);\n dfs(matrix, i, col-1, matrix[i][col-1], atlantic);\n }\n for (int i=0; i<row; i++) {\n for (int j=0; j<col; j++) {\n if (pacific[i][j] && atlantic[i][j]) {\n List<Integer> currentResult = new ArrayList<>();\n currentResult.add(i);\n currentResult.add(j);\n result.add(currentResult);\n }\n }\n }\n return result;\n }\n \n public void dfs(int [][] matrix, int i, int j, int preHeight, boolean [][] ocean) {\n if (i < 0 || j < 0 || i >= matrix.length || j >= matrix[0].length || preHeight > matrix[i][j] || ocean[i][j])\n return;\n ocean[i][j] = true;\n dfs(matrix, i+1, j, matrix[i][j], ocean);\n dfs(matrix, i-1, j, matrix[i][j], ocean);\n dfs(matrix, i, j+1, matrix[i][j], ocean);\n dfs(matrix, i, j-1, matrix[i][j], ocean);\n }\n}\n```
14
0
['Depth-First Search', 'Recursion', 'Java']
3
pacific-atlantic-water-flow
DFS Python3, easy to understand with comments.
dfs-python3-easy-to-understand-with-comm-n0pt
Please +1 if you like the solution\n\nclass Solution:\n def pacificAtlantic(self, matrix: List[List[int]]) -> List[List[int]]:\n if not matrix or not
rotikapdamakan
NORMAL
2020-11-30T15:57:20.802523+00:00
2020-11-30T15:57:56.435576+00:00
1,109
false
Please +1 if you like the solution\n```\nclass Solution:\n def pacificAtlantic(self, matrix: List[List[int]]) -> List[List[int]]:\n if not matrix or not matrix[0]:\n return []\n \n # list which will have both the coordinates\n pacific = set()\n atlantic = set()\n # get the number of rows and columns\n m,n = len(matrix), len(matrix[0])\n\n # define left, right, up, down\n directions = [(-1,0),(1,0),(0,1),(0,-1)]\n\n # define the dfs traversal\n def dfs(visited, x,y):\n visited.add((x,y))\n for dx, dy in directions:\n new_x, new_y = x + dx, y + dy\n\n # if the coordinates are valid and if c(i) > c (i-1)\n if 0 <= new_x < m and 0 <= new_y < n and (new_x, new_y) not in visited and matrix[new_x][new_y] >= matrix[x][y]:\n dfs (visited, new_x, new_y)\n\n # iterate for rows\n for i in range(m):\n dfs(pacific, i , 0)\n dfs(atlantic, i, n-1)\n\n # iterate for columns\n for j in range(n):\n dfs(pacific, 0 , j)\n dfs(atlantic, m-1, j)\n\n # return the matching coordinates\n return list(pacific.intersection(atlantic))\n\n```
14
0
['Depth-First Search', 'Python3']
2
pacific-atlantic-water-flow
C++ || Shortest Solution || DFS || Very easy to understand
c-shortest-solution-dfs-very-easy-to-und-rzsz
\nclass Solution {\npublic:\n\n \n void dfs(int i,int j,vector<vector<int>>& height, vector<vector<bool>> &ocean)\n {\n \n int n=height.siz
mittaldarpann
NORMAL
2021-08-05T10:46:04.768582+00:00
2021-08-05T10:59:50.957278+00:00
1,634
false
```\nclass Solution {\npublic:\n\n \n void dfs(int i,int j,vector<vector<int>>& height, vector<vector<bool>> &ocean)\n {\n \n int n=height.size();\n int m=height[0].size();\n if(ocean[i][j]==false)\n ocean[i][j]=true;\n if(i>0 && height[i-1][j]>=height[i][j] && ocean[i-1][j]==false)dfs(i-1,j,height,ocean);\n if(j>0 && height[i][j-1]>=height[i][j] && ocean[i][j-1]==false)dfs(i,j-1,height,ocean);\n if(i<n-1 && height[i+1][j]>=height[i][j] && ocean[i+1][j]==false)dfs(i+1,j,height,ocean);\n if(j<m-1 && height[i][j+1]>=height[i][j] && ocean[i][j+1]==false)dfs(i,j+1,height,ocean);\n return;\n }\n \n vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {\n vector<vector<int>> ans;\n \n \n int n=heights.size();\n int m=heights[0].size();\n vector<vector<bool>> pacific(n+1,vector<bool>(m+1,false));\n vector<vector<bool>> atlantic(n+1,vector<bool>(m+1,false));\n \n \n //Check Edges for Pacific ocean\n \n for(int i=0;i<n;i++)\n {\n for(int j=0;j<m;j++)\n {\n if(i==0 || j==0)\n dfs(i,j,heights,pacific); \n }\n }\n \n \n //Check Edges for Atlantic ocean\n for(int i=0;i<n;i++)\n {\n for(int j=0;j<m;j++)\n {\n if(i==n-1 || j==m-1)\n dfs(i,j,heights,atlantic); \n }\n }\n \n \n //If water can flow from a cell in both atlantic and pacific add that to our answer.\n for(int i=0;i<n;i++)\n {\n for(int j=0;j<m;j++)\n {\n if(atlantic[i][j]==true && pacific[i][j]==true)\n ans.push_back({i,j});\n }\n }\n return ans;\n \n }\n};\n\n```\nPlease upvote if it was helpful.\n
13
0
['Depth-First Search', 'C', 'C++']
2
pacific-atlantic-water-flow
C++ solution with short explanation | DFS
c-solution-with-short-explanation-dfs-by-uuso
The main idea is to try to go from the edges ("oceans") to other nodes. By keeping track of reached nodes from each "ocean" we can find the nodes which can reac
aarkalyk
NORMAL
2020-07-28T15:00:00.950058+00:00
2020-07-28T15:06:18.350898+00:00
1,812
false
The main idea is to try to go from the edges ("oceans") to other nodes. By keeping track of reached nodes from each "ocean" we can find the nodes which can reach both oceans.\n\n```\nclass Solution {\nprivate:\n void dfs(const vector<vector<int>>& matrix, const vector<pair<int, int>> &coords, vector<vector<bool>> &visited, int i, int j) {\n visited[i][j] = true;\n \n for(auto &coord : coords) {\n int next_i = coord.first + i;\n int next_j = coord.second + j;\n \n\t\t\t// since we\'re going backwards (from "ocean" instead of to) we want the next node\'s value to be equal to or more than the current node\'s value\n if (is_in_bounds(matrix, next_i, next_j) && !visited[next_i][next_j] && matrix[next_i][next_j] >= matrix[i][j]) {\n dfs(matrix, coords, visited, next_i, next_j);\n }\n }\n }\n \n bool is_in_bounds(const vector<vector<int>>& matrix, int i, int j) {\n return i >= 0 && j >= 0 && i < matrix.size() && j < matrix[0].size();\n }\n \npublic:\n vector<vector<int>> pacificAtlantic(const vector<vector<int>>& matrix) {\n if (matrix.empty())\n return vector<vector<int>>();\n \n const vector<pair<int, int>> coords = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};\n \n int n = matrix.size(), m = matrix[0].size();\n vector<vector<bool>> visited_atlantic(n, vector<bool>(m, false));\n vector<vector<bool>> visited_pacific(n, vector<bool>(m, false));\n \n for(int i = 0; i < n; i++) {\n\t\t // left edge for pacific ocean\n dfs(matrix, coords, visited_pacific, i, 0);\n\t\t // right edge for atlantic ocean\n dfs(matrix, coords, visited_atlantic, i, m - 1);\n }\n for(int j = 0; j < m; j++) {\n // top edge for pacific ocean\n dfs(matrix, coords, visited_pacific, 0, j);\n\t\t\t// bottom edge for atlantic ocean\n dfs(matrix, coords, visited_atlantic, n - 1, j);\n }\n \n vector<vector<int>> result;\n\t\t// find the nodes that can reach both oceans\n for(int i = 0; i < n; i++)\n for(int j = 0; j < m; j++)\n if (visited_pacific[i][j] && visited_atlantic[i][j])\n result.push_back({ i, j });\n \n return result;\n }\n};\n\n\n\n\n\n\n\n\n```
13
1
['Depth-First Search', 'C']
0
pacific-atlantic-water-flow
CPP Solution (2 ways) DFS, BFS with Explanation
cpp-solution-2-ways-dfs-bfs-with-explana-mqod
There seem to be a lack of explanation in all the CPP contributions even for some voted highly. So here\'s one with explanations. \n\nSkip to (2) if you want th
raptor16
NORMAL
2019-07-01T21:57:33.063065+00:00
2019-07-09T03:12:25.121914+00:00
1,435
false
There seem to be a lack of explanation in all the CPP contributions even for some voted highly. So here\'s one with explanations. \n\n**Skip to (2) if you want the working solution**\n\nFirst Attempt: *Solution1 class*\n(1) The idea is for every single cell, we want to check if it can reach the atlantic, pacific, none, or both. I first started with two separate functions, one for checking the atlantic and one for checking pacific and then comparing the two...but this is too inefficient so I merged the two functions. \n\nWe know we can reach the pacific if we ended at row 0 or col 0 and the atlantic if we reached last row and last column, so these are the base case. But there is also a special case where we can jump from a NONE state to a BOTH state which is when we reached the \'hot corners\' the upper right and bottom left which are connected to both the atlantic and pacific.\n\nTo check if we can reach the edges, it\'s simple: we just need to do either BFS or DFS (recursive or iterative with stacks). So from that cell we see if water can spill to its neighbours and the neighbours\' neighbours etc. \n\n```\n\nclass Solution1 {\nprivate: \n \n enum class State\n {\n PACIFIC,\n ATLANTIC, \n BOTH, \n NONE\n };\n \n int rowSize, colSize;\n vector<int> offset = {0, 1, 0, -1, 0};\n \n bool outOfBounds(int row, int col){\n return row < 0 || col < 0 || row >= rowSize || col >= colSize;\n }\n \n State flowToPacificOrAtlantic(vector<vector<int>>& matrix, int row, int col, vector<vector<bool>> visited, State prevState){ \n if (prevState == State::BOTH)\n return State::BOTH;\n \n \n if((row == rowSize -1 && col == 0) || (row == 0 && col== colSize -1)) // top right and bottom left (Special corners)\n return State::BOTH;\n \n // Update the state: We can only go from None to Pacific or Atlantic or from Pacific or Atlantic to both from here on. \n if (row == 0 || col == 0){ // Pacific Ocean\n if (prevState == State::ATLANTIC){ \n return prevState = State::BOTH; // We already previously reached the atlantic, so we change the state to both\n } else{\n prevState = State::PACIFIC;\n }\n } else if (row == rowSize -1 || col== colSize -1){ // Atlantic Ocean\n if (prevState == State::PACIFIC){\n return prevState = State::BOTH; // We already previously reached the pacific, so we change the state to both\n } else {\n prevState = State::ATLANTIC;\n }\n }\n \n // We need to keep track of the visited ones for cycles since we are checking equal water levels as well which means we can get\n // stuck in a cycle of the same values\n visited[row][col] = true; \n \n int currWaterLevel = matrix[row][col];\n for (int i = 1; i<offset.size(); i++){ // Go to left right up down using the offset --> (+1, +0) (+0, +1), (-1, +0), (+0, -1)\n int r = row + offset[i], c = col + offset[i-1]; // assign variable to record the row and col of the up down left right \n if(!outOfBounds(r , c) && \n currWaterLevel >= matrix[r][c] && // current water level is higher than the surrounding water\n !visited[r][c]){\n \n prevState = flowToPacificOrAtlantic(matrix, r, c, visited, prevState); // Update the state\n }\n }\n return prevState;\n }\n \npublic:\n vector<vector<int>> pacificAtlantic(vector<vector<int>>& matrix) {\n vector<vector<int>> result;\n rowSize = matrix.size(); \n if (rowSize == 0)\n return result;\n colSize = matrix[0].size();\n \n \n vector<vector<bool>> visited(rowSize, vector<bool> (colSize, 0));\n for (int row = 0; row < rowSize; row++){\n for (int col = 0; col<colSize; col++){\n if (flowToPacificOrAtlantic(matrix, row, col, visited, State::NONE) == State::BOTH){\n result.push_back({row, col});\n }\n }\n } \n return result;\n }\n};\n```\n\nBut since we are recursing over every single cell for a very large m and n, this becomes very inefficeint. All we really need to do is to check for the edges and find how far the pacific ocean and atlantic ocean spill respectively. This is where the second approach comes in. \n\nSecond Solution: *Solution class*\n(2) The second approach is much more efficient as mentioned before. We need to record the \'map\' of where the pacific and atlantic ocean can spill into. So we need two separate maps one for the atlantic and one for the pacific. Once done, we just compare to see where the common areas where both the atlantic and pacific water can \'spill upwards\' from the edges. By spill upwards I mean imagine the water from the edges flowing up hill, hence we are looking for bigger numbers. This is just the reverse logic from (1). \n\n\n\n```\n\nclass Solution {\nprivate: \n\n int rowSize, colSize;\n vector<int> offset = {0, 1, 0, -1, 0};\n \n bool outOfBounds(int row, int col){\n return row < 0 || col < 0 || row >= rowSize || col >= colSize;\n }\n \n void flowToPacificOrAtlantic(vector<vector<int>>& matrix, int row, int col, vector<vector<bool>>& visited){ \n visited[row][col] = true; \n \n int currWaterLevel = matrix[row][col];\n for (int i = 1; i<offset.size(); i++){ // Go to left right up down using the offset --> (+1, +0) (+0, +1), (-1, +0), (+0, -1)\n int r = row + offset[i], c = col + offset[i-1]; \n if(!outOfBounds(r , c) && \n currWaterLevel <= matrix[r][c] && // !!! current water level is lower than the surrounding water !!!\n !visited[r][c]){\n \n flowToPacificOrAtlantic(matrix, r, c, visited);\n }\n }\n }\n \npublic:\n vector<vector<int>> pacificAtlantic(vector<vector<int>>& matrix) {\n vector<vector<int>> result;\n rowSize = matrix.size(); \n if (rowSize == 0)\n return result;\n colSize = matrix[0].size();\n \n // initialize the maps to 0\n vector<vector<bool>> pacific(rowSize, vector<bool> (colSize, 0)); \n vector<vector<bool>> atlantic(rowSize, vector<bool> (colSize, 0));\n\n for (int row = 0; row < rowSize; row++){\n flowToPacificOrAtlantic(matrix, row, 0, pacific); // column 0 (pacific)\n flowToPacificOrAtlantic(matrix, row, colSize -1, atlantic); // column end (atlantic)\n } \n for (int col = 0; col < colSize; col++){\n flowToPacificOrAtlantic(matrix, 0, col, pacific); // row 0 (pacific)\n flowToPacificOrAtlantic(matrix, rowSize -1, col, atlantic); // row end (atlantic)\n }\n\n // Compare the two \'maps\' and find where they have a common 1\n for (int row = 0; row<rowSize; row++){\n for(int col = 0; col<colSize; col++){\n if (pacific[row][col] == 1 && atlantic[row][col] == 1){\n result.push_back({row, col});\n }\n } \n }\n \n return result;\n }\n};\n\n```\n\nEdit: \nI am adding BFS rather than the DFS for finding the visited matrix. This code is very similar to DFS except it uses a queue which prevents additional space incurred by use of the call stack. Just change ```flowToPacificOrAtlantic``` to ```BFS``` from solution 2 and everything should work. \n\n```\nvoid BFS(vector<vector<int>> & matrix, int row, int col, vector<vector<bool>> &visited){\n queue<pair<int, int>> todo;\n todo.push(make_pair(row, col));\n visited[row][col] = 1;\n while (!todo.empty()){\n pair<int, int> p = todo.front(); \n int currWaterLevel = matrix[p.first][p.second];\n todo.pop(); \n // check neighbours of todo\n for (int i = 1; i<offset.size(); i++){\n int r = p.first + offset[i], c = p.second + offset[i-1];\n if (!outOfBounds(r, c) && currWaterLevel <= matrix[r][c] && !visited[r][c]){\n todo.push(make_pair(r, c));\n visited[r][c] = 1;\n }\n }\n }\n }\n```
13
0
[]
1
pacific-atlantic-water-flow
Java DFS Solution beat 99.99% and sharing my thoughts!!!666
java-dfs-solution-beat-9999-and-sharing-7k2d8
So the basic idea is start from 4 boards, for the points in the first row and column, they are definitely connect with Pacific Ocean, and for the points in the
yunwei_qiu
NORMAL
2018-06-18T06:31:43.417193+00:00
2018-09-05T17:13:59.295861+00:00
2,194
false
So the basic idea is start from 4 boards, for the points in the first row and column, they are definitely connect with Pacific Ocean, and for the points in the last row and columnm, they are connected with A Ocean. Then, run dfs first time to mark these points that is able to connect with Pacifica Ocean as \'P\', run dfs second time to find the points that has been already marked as "P", if its \'A\' then we find a point is able to connect with both P and A. Thus the total time complexity will be O(2 * m * n)\n```\nprivate static final int[][] directions = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};\n public List<int[]> pacificAtlantic(int[][] matrix) {\n List<int[]> res = new ArrayList<>();\n if (matrix == null || matrix.length == 0) return res;\n int m = matrix.length;\n int n = matrix[0].length;\n char[][] visited = new char[m][n];\n for (int col = 0; col < n; col++) {\n dfs(matrix, 0, col, visited, \'P\', res);\n }\n for (int row = 0; row < m; row++) {\n dfs(matrix, row, 0, visited, \'P\', res);\n }\n \n for (int col = 0; col < n; col++) {\n dfs(matrix, m - 1, col, visited, \'A\', res);\n }\n for (int row = 0; row < m; row++) {\n dfs(matrix, row, n - 1, visited, \'A\', res);\n }\n return res;\n }\n \n private void dfs(int[][] matrix, int row, int col, char[][] visited, char ch, List<int[]> res) {\n if (visited[row][col] == \'P\' && ch == \'A\') res.add(new int[]{row, col});\n visited[row][col] = ch;\n for (int[] dir : directions) {\n int x = row + dir[0];\n int y = col + dir[1];\n if (x < 0 || x >= matrix.length || y < 0 || y >= matrix[0].length || matrix[row][col] > matrix[x][y] || visited[x][y] == ch) continue;\n dfs(matrix, x, y, visited, ch, res);\n }\n \n }
13
1
[]
4
pacific-atlantic-water-flow
C++ Solution || BFS Implementation || Easy to understand clean code
c-solution-bfs-implementation-easy-to-un-c119
First of all many of us might be having some issues understanding the problem.\n\nConfusion : Is water going from ocean to island?\n\nNo, actually we are given
ngaur6834
NORMAL
2021-04-30T10:49:42.713657+00:00
2021-04-30T10:51:33.480070+00:00
719
false
First of all many of us might be having some issues understanding the problem.\n\n**Confusion : Is water going from ocean to island?**\n\nNo, actually we are given an island and we are asked if we supply a specific coordinate with water then tell us the flow of water.\nCan the water flow to both pacific and atlantic ocean from a specific coordinate ? If yes then add that coordinate in your answer.\n\nHope you got the point!\n\n\tvector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {\n int n = heights.size();\n int m = heights[0].size();\n \n\t\t//the points from where its possible to flow water to pacific\n vector<vector<bool> > pacific(n, vector<bool> (m,false));\n\t\t//same for atlantic\n vector<vector<bool> > atlantic(n, vector<bool> (m,false));\n \n\t\t//utility queues for both oceans\n queue<pair<int,int> > pq;\n queue<pair<int,int>> aq;\n \n\t\t//push the respective boundary elements to the pacific and atlantic queue and bool array\n for(int i=0; i<n; i++){\n for(int j=0; j<m; j++){\n if(i == 0 || j == 0){\n pq.push({i,j});\n pacific[i][j] = true;\n }\n \n if(i == n-1 || j == m-1){\n aq.push({i,j});\n atlantic[i][j] = true;\n }\n }\n }\n \n\t\t//final answer array containing commom points\n vector<vector<int> > ans;\n \n bfs(heights, pq, pacific);\n bfs(heights, aq, atlantic);\n \n for(int i=0; i<n; i++){\n for(int j=0; j<m; j++){\n if(pacific[i][j] && atlantic[i][j]){\n ans.push_back({i,j});\n }\n }\n }\n \n return ans;\n \n }\n \n void bfs(vector<vector<int>> &heights, queue<pair<int,int> > q, vector<vector<bool> > &vis){\n int n = heights.size();\n int m = heights[0].size();\n \n\t\t//direction arrays\n vector<int> dx = {0,0,1,-1};\n vector<int> dy = {-1,1,0,0};\n \n while(!q.empty()){\n int x = q.front().first;\n int y = q.front().second;\n \n q.pop();\n \n\t\t\t//iterate all 4 directions\n for(int i=0; i<4; i++){\n int nx = x + dx[i];\n int ny = y + dy[i];\n \n\t\t\t\t//along with all the eligibility criteria the next coordinates height must be greater than or equal to the current coordinates heights cause we are moving from ocean to island and\n\t\t\t\t//we want the water to go from island to ocean.\n if(nx >= 0 && ny >= 0 && nx < n && ny < m && vis[nx][ny] == false && heights[nx][ny] >= heights[x][y]){\n q.push({nx,ny});\n vis[nx][ny] = true;\n }\n }\n }\n \n return ;\n }\n\t\n**ps: feel free to ask any question in the comment section : )**
12
0
['Breadth-First Search', 'C']
2
pacific-atlantic-water-flow
Python solution with detailed explanation
python-solution-with-detailed-explanatio-v158
Solution\n\nPacific Atlantic Water Flow https://leetcode.com/problems/pacific-atlantic-water-flow/\n\nBrute Force Solution\n For every point in the grid, find w
gabbu
NORMAL
2017-01-27T18:15:22.553000+00:00
2017-01-27T18:15:22.553000+00:00
9,380
false
**Solution**\n\n**Pacific Atlantic Water Flow** https://leetcode.com/problems/pacific-atlantic-water-flow/\n\n**Brute Force Solution**\n* For every point in the grid, find whether it can reach both pacific and atlantic. You can use standard DFS or BFS for this. There are mn points and DFS/BFS is O(2mn).\n\n**Optimized Solution**\n* On the other hand, we can consider the flip side. We can let the pacific and atlantic ocean "flow into" the matrix as much as possible, using 2 boolean arrays, one for each ocean. The result are the points that are true in both boolean table.\n* Two Queue and add all the Pacific border to one queue; Atlantic border to another queue.\n* Keep a visited matrix for each queue. In the end, add the cell visited by two queue to the result.\n* Water flows from ocean to the cell. Since water can only flow from high/equal cell to low cell, **add the neighboor cell with height larger or equal to current cell to the queue and mark as visited**.\n```\nif 0<=x1<N and 0<=y1<M and not visited[x1][y1] and matrix[x1][y1] >= matrix[x][y]\n```\n* Note we can also use DFS here. Do a DFS from every pacific point and then from every atlantic point. Take an intersection later.\n* https://discuss.leetcode.com/topic/62280/simple-commented-java-solution-with-thinking-progress-o-n\n* https://discuss.leetcode.com/topic/62379/java-bfs-dfs-from-ocean\n\n```\nfrom Queue import Queue\nclass Solution(object):\n def bfs(self, q, matrix, visited):\n N, M = len(matrix), len(matrix[0])\n while q.empty() == False:\n (x,y) = q.get()\n candidates = [(x+1,y), (x-1,y), (x,y+1), (x,y-1)]\n for (x1,y1) in candidates:\n if 0<=x1<N and 0<=y1<M and not visited[x1][y1] and matrix[x1][y1] >= matrix[x][y]:\n q.put((x1,y1))\n visited[x1][y1]=True\n return\n \n def initialize_q(self, N, M, pac_q, atl_q, pac_visited, atl_visited):\n for i in range(N):\n pac_q.put((i,0))\n atl_q.put((i, M-1))\n pac_visited[i][0], atl_visited[i][M-1] = True, True\n \n for j in range(M):\n pac_q.put((0,j))\n atl_q.put((N-1,j))\n pac_visited[0][j], atl_visited[N-1][j] = True, True\n return\n \n def pacificAtlantic(self, matrix):\n """\n :type matrix: List[List[int]]\n :rtype: List[List[int]]\n """\n if matrix == []:\n return []\n N, M = len(matrix), len(matrix[0])\n pac_q, atl_q = Queue(), Queue()\n pac_visited = [[False]*M for _ in range(N)]\n atl_visited = [[False]*M for _ in range(N)] \n \n self.initialize_q(N, M, pac_q, atl_q, pac_visited, atl_visited)\n self.bfs(pac_q, matrix, pac_visited) \n self.bfs(atl_q, matrix, atl_visited) \n \n result = []\n for i in range(N):\n for j in range(M):\n if pac_visited[i][j] and atl_visited[i][j]:\n result.append([i,j])\n \n return result\n```
12
1
[]
0
pacific-atlantic-water-flow
Helpful DFS JavaScript solution
helpful-dfs-javascript-solution-by-camet-1uv6
If you\'re like me, this may be the first DFS problem you\'ve ever come across. I looked at some answers, they broke my brain, and I had to leave and learn abou
cametumbling
NORMAL
2022-02-09T19:24:35.469321+00:00
2022-02-09T22:25:16.772730+00:00
759
false
If you\'re like me, this may be the first DFS problem you\'ve ever come across. I looked at some answers, they broke my brain, and I had to leave and learn about DFS and come back (which is a bit more difficult if JavaScript is your primary language). I\'d recommend doing that. But here is the solution I wish had existed.\n\nIn a nutshell, Depth First Search takes a starting point (node or vertex, in this problem one of the squares in the matrix) and checks to see if it can find a path*. It goes all along a path until it\'s reached the end (in contrast to BFS, which checks one next node around it at a time before moving on). If the function has visited a node, it marks it off its list and moves on, storing the result in an adjacency matrix (used here) or adjacency list. This is the best explanation of the concept I\'ve seen: [https://xkcd.com/761/](http://)\n\n\\* *In this case, we\'ll write a dfs function to check if water can flow from a node adjacent to the ocean up to a high point--if that high point is found from both the pacific and atlantic oceans, it goes into our result. (Despite the problem statement of finding downhill flow, we must understand that the best approach to this problem is the opposite: starting at downhill points and working uphill.)*\n\nDFS can be implemented in several ways. Here we use recursion to check neighboring nodes. Stacks are also commonly used. \n\nThe fastest solution uses dynamic programming; you can find that solution in someone else\'s post on the discussion board. The solution here is currently the most comfortable for me, and I am confident that at my current level I could explain it at interview, but if that changes I will update this. It currently beats about 70%. \n\n```\nconst pacificAtlantic = (matrix) => {\n if (!matrix.length) return [];\n \n let numRows = matrix.length;\n let numCols = matrix[0].length;\n \n //create two adjacency matrices for results of atlantic and pacific dfs\n //(if a node can reach an ocean, it goes in that matrix)\n const pacific = new Array(numRows).fill().map(() => Array(numCols).fill(false))\n const atlantic = new Array(numRows).fill().map(() => Array(numCols).fill(false))\n \n /*KEY POINT: dfs will be run from the ocean inwards, not vice versa\n (from the ocean-adjacent nodes to the highest point(s))*/\n \n //dfs works by marking successfully visited squares in matrix as true\n //remember we\'re going from ocean inland\n const dfs = (r, c, current, ocean) =>{ //r=row c=column ocean=pacific/atlantic current=the node we\'re checking\n //base case: return if out of bounds\n if (r < 0 || c < 0 || r >= numRows || c >= numCols) return;\n //base case: return if our current node is larger than the surrounding nodes, because we are only marking node as true if it is larger than the next...remember we are working upwards to the highest point. This is a bit confusing, but look at the inputs: when we run this recursively, below, if N, S, E, or W are less than the current node, we\'ll return, because they need to be HIGHER to work upwards.\n if (matrix[r][c] < current) return;\n //base case: return if this node already marked (in ocean), thus already visited\n if (ocean[r][c]) return;\n //if we\'re here it means the conditions have been successfully met and thus we can reach the ocean, so we mark this node true (water can flow here) in that ocean\n ocean[r][c] = true;\n //call dfs recursively on each of the surrounding cells (ie N,S,E,W)\n dfs(r+1, c, matrix[r][c], ocean);\n dfs(r-1, c, matrix[r][c], ocean);\n dfs(r, c+1, matrix[r][c], ocean);\n dfs(r, c-1, matrix[r][c], ocean);\n };\n \n /*the pacfic touches the top and left sides of the matrix (N & E)\n and the atlantic touches the right and bottom sides (W & S)\n thus...*/\n //we run DFS for the top and bottom rows\n for (let col=0; col < numCols; col++){\n dfs(0, col, Number.MIN_SAFE_INTEGER, pacific);\n dfs(numRows-1, col, Number.MIN_SAFE_INTEGER, atlantic);\n }\n //and for the first and last columns\n for (let row = 0; row < numRows; row++){\n dfs(row, 0, Number.MIN_SAFE_INTEGER, pacific)\n dfs(row, numCols-1, Number.MIN_SAFE_INTEGER, atlantic)\n }\n\n //add to result if exists in both pacific and atlantic\n let result = [];\n for (let i=0; i < numRows; i++){\n for (let j=0; j < numCols; j++){\n if (atlantic[i][j] && pacific[i][j]){\n result.push([i, j]);\n }\n }\n }\n return result;\n};\n```
11
0
['JavaScript']
1
pacific-atlantic-water-flow
C++ BFS Solution Explained
c-bfs-solution-explained-by-ahsan83-9ta8
Runtime: 76 ms, faster than 80.07% of C++ online submissions for Pacific Atlantic Water Flow.\nMemory Usage: 18.3 MB, less than 5.28% of C++ online submissions
ahsan83
NORMAL
2020-10-20T18:08:18.676151+00:00
2020-10-20T18:08:18.676197+00:00
1,352
false
Runtime: 76 ms, faster than 80.07% of C++ online submissions for Pacific Atlantic Water Flow.\nMemory Usage: 18.3 MB, less than 5.28% of C++ online submissions for Pacific Atlantic Water Flow.\n\n\n```\nAs we want grid position from where water can reach both pacific and atlantic ocean, we can \nalso think it as grid positions which are reachable both from pacific and atlantic ocean boundary.\n\nRun BFS from all pacific boundary positions and track reachable grid positions, also run BFS from\natlantic boundary postions and track reachable grid positions. Grid position which are both\nreachable from pacific and atlantic are the result. From boundary positions water can flow in to\nneighbor grid positions which have greater or equal height.\n\nExample: \n\nYellow = Reachable from pacific boundary\nBlue = Reachable from atlantic boundary\nGreen = Reachable from both boundary\n```\n\n![image](https://assets.leetcode.com/users/images/e58f1f23-3ec8-4f7c-b5dd-87e19661bd95_1603217239.0575259.png)\n\n\n```\nclass Solution {\npublic:\n \n // run bfs to track reachable grid position from pacific or atlantic boundary\n void bfs(int m, int n, queue<pair<int,int>>&Q, vector<vector<int>>& grid, vector<vector<bool>>&visited)\n {\n int rowOffset[] = {0,0,1,-1};\n int colOffset[] = {1,-1,0,0};\n int currentHeight;\n int cx,cy;\n int px,py;\n \n while(!Q.empty())\n {\n cx = Q.front().first;\n cy = Q.front().second;\n currentHeight = grid[cx][cy];\n \n Q.pop();\n \n for(int k=0;k<4;k++)\n {\n px = cx + rowOffset[k];\n py = cy + colOffset[k];\n \n // child node can be reached from current nodes if \n // greater or equal in height compared to current node height\n if(px>=0 && px<m && py>=0 && py<n && grid[px][py]>=currentHeight && !visited[px][py])\n {\n visited[px][py] = true;\n Q.push({px,py});\n }\n }\n }\n }\n \n vector<vector<int>> pacificAtlantic(vector<vector<int>>& grid) {\n \n vector<vector<int>>result;\n \n int m = grid.size();\n if(m==0) return result;\n \n int n = grid[0].size();\n if(n==0) return result;\n \n // track nodes reachable from pacific boundary\n vector<vector<bool>>pacificVisited(m,vector<bool>(n,false));\n \n // track nodes reachable from atlantic boundary\n vector<vector<bool>>atlanticVisited(m,vector<bool>(n,false));\n \n queue<pair<int,int>>Q;\n \n // add pacific boundary nodes in to queue\n for(int i=0;i<n;i++)\n {\n if(!pacificVisited[0][i])\n {\n pacificVisited[0][i] = true;\n Q.push({0,i}); \n }\n }\n\n // add pacific boundary nodes in to queue \n for(int i=1;i<m;i++)\n {\n if(!pacificVisited[i][0])\n {\n pacificVisited[i][0] = true;\n Q.push({i,0}); \n }\n }\n \n // run bfs from pacific boundary nodes\n bfs(m,n,Q,grid,pacificVisited);\n \n // add atlantic boundary nodes\n for(int i=0;i<n;i++)\n {\n if(!atlanticVisited[m-1][i])\n {\n atlanticVisited[m-1][i] = true;\n Q.push({m-1,i}); \n }\n }\n\n // add atlantic boundary nodes \n for(int i=0;i<m-1;i++)\n {\n if(!atlanticVisited[i][n-1])\n {\n atlanticVisited[i][n-1] = true;\n Q.push({i,n-1}); \n }\n }\n \n // run bfs from atlantic boundary nodes\n bfs(m,n,Q,grid,atlanticVisited);\n \n // push nodes in to result vector which are reachable both from pacific and atlantic boundary\n for(int i=0;i<m;i++)\n for(int j=0;j<n;j++)\n if(pacificVisited[i][j] && atlanticVisited[i][j])\n result.push_back({i,j});\n \n return result;\n }\n};\n```
11
1
['Breadth-First Search', 'C']
0
pacific-atlantic-water-flow
82.1 (Approach 1) | ( O(m * n) )✅ | Python & C++(Step by step explanation)✅
821-approach-1-om-n-python-cstep-by-step-36oz
Intuition\nThe problem asks to find the coordinates of cells from which water can flow to both the Pacific and the Atlantic oceans. Cells can flow water to adja
monster0Freason
NORMAL
2024-02-13T20:12:39.055625+00:00
2024-02-13T20:12:39.055655+00:00
2,282
false
# Intuition\nThe problem asks to find the coordinates of cells from which water can flow to both the Pacific and the Atlantic oceans. Cells can flow water to adjacent cells if the adjacent cell has a higher or equal height. We need to find cells where water can flow to the Pacific Ocean and to the Atlantic Ocean.\n\n# Approach\n![image.png](https://assets.leetcode.com/users/images/0ef801c9-49b9-487e-824f-00b6316a35fa_1707855142.5285482.png)\n\n\n1. **Defining DFS Functions**:\n - We\'ll start by defining a Depth-First Search (DFS) function to traverse the matrix and mark cells reachable from the Pacific and Atlantic oceans. This function will be called from the borders of the matrix.\n \n2. **Traversing Borders**:\n - We\'ll iterate through the top and bottom rows of the matrix, as well as the leftmost and rightmost columns. For each cell on these borders, we\'ll perform DFS to mark cells reachable from the Pacific Ocean if it\'s a top or left border cell, and from the Atlantic Ocean if it\'s a bottom or right border cell.\n\n3. **DFS Traversal**:\n - During DFS traversal, starting from a border cell, we\'ll explore adjacent cells in all four directions (up, down, left, and right).\n - We\'ll only move to adjacent cells with heights greater than or equal to the current cell\'s height to simulate water flowing.\n - We\'ll continue DFS until we can\'t move further or until we\'ve visited a cell already marked as reachable.\n - Each time we visit a cell, we\'ll mark it as reachable from the respective ocean.\n\n4. **Checking Accessibility**:\n - After marking cells reachable from both oceans, we\'ll iterate through all cells in the matrix.\n - For each cell, we\'ll check if it\'s marked as reachable from both the Pacific and Atlantic oceans. If so, we\'ll add its coordinates to the result list.\n\n5. **Returning Results**:\n - Finally, we\'ll return the list of coordinates representing cells accessible from both oceans.\n\nThis approach effectively identifies cells that can flow water to both the Pacific and Atlantic oceans, allowing us to find areas that can reach both sides of the border.\n\n# Complexity\n- Time complexity: \\(O(m * n)\\), where \\(m\\) is the number of rows and \\(n\\) is the number of columns in the matrix. We perform DFS from the borders, and each cell is visited exactly once.\n- Space complexity: \\(O(m * n)\\) for the sets used to track reachable cells, and \\(O(k)\\) for the result list, where \\(k\\) is the number of cells accessible from both oceans.\n\n\n### Python Solution:\n\n```python\nclass Solution:\n def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:\n rows, cols = len(heights), len(heights[0])\n pac, atl = set(), set()\n\n # Define DFS function to traverse the matrix and mark cells reachable\n def dfs(r, c, visit, prevHeight):\n # Base cases for termination of DFS traversal\n if (\n (r, c) in visit\n or r < 0\n or c < 0\n or r == rows\n or c == cols\n or heights[r][c] < prevHeight\n ):\n return\n visit.add((r, c))\n # Recursive calls for DFS traversal in four directions\n dfs(r + 1, c, visit, heights[r][c])\n dfs(r - 1, c, visit, heights[r][c])\n dfs(r, c + 1, visit, heights[r][c])\n dfs(r, c - 1, visit, heights[r][c])\n\n # DFS from top and bottom borders to mark cells reachable by Pacific and Atlantic\n for c in range(cols):\n dfs(0, c, pac, heights[0][c])\n dfs(rows - 1, c, atl, heights[rows - 1][c])\n\n # DFS from left and right borders to mark cells reachable by Pacific and Atlantic\n for r in range(rows):\n dfs(r, 0, pac, heights[r][0])\n dfs(r, cols - 1, atl, heights[r][cols - 1])\n\n # Find cells reachable from both oceans and store their coordinates in res\n res = []\n for r in range(rows):\n for c in range(cols):\n if (r, c) in pac and (r, c) in atl:\n res.append([r, c])\n return res\n```\n\n### C++ Solution:\n\n```cpp\nclass Solution {\npublic:\n vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {\n int m = heights.size();\n int n = heights[0].size();\n \n // Create matrices to mark visited cells for both oceans\n vector<vector<bool>> pacific(m, vector<bool>(n));\n vector<vector<bool>> atlantic(m, vector<bool>(n));\n \n // DFS traversal from top and bottom borders for both oceans\n for (int i = 0; i < m; i++) {\n dfs(heights, pacific, i, 0, m, n);\n dfs(heights, atlantic, i, n - 1, m, n);\n }\n \n // DFS traversal from left and right borders for both oceans\n for (int j = 0; j < n; j++) {\n dfs(heights, pacific, 0, j, m, n);\n dfs(heights, atlantic, m - 1, j, m, n);\n }\n \n // Find cells reachable from both oceans and store their coordinates in res\n vector<vector<int>> res;\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (pacific[i][j] && atlantic[i][j]) {\n res.push_back({i, j});\n }\n }\n }\n \n return res;\n }\nprivate:\n // DFS function to mark reachable cells from a given cell\n void dfs(vector<vector<int>>& heights, vector<vector<bool>>& visited,\n int i, int j, int m, int n) {\n \n visited[i][j] = true;\n \n // Recursive calls for DFS traversal in four directions\n if (i > 0 && !visited[i - 1][j] && heights[i - 1][j] >= heights[i][j]) {\n dfs(heights, visited, i - 1, j, m, n);\n }\n if (i < m - 1 && !visited[i + 1][j] && heights[i + 1][j] >= heights[i][j]) {\n dfs(heights, visited, i + 1, j, m, n);\n }\n if (j > 0 && !visited[i][j - 1] && heights[i][j - 1] >= heights[i][j]) {\n dfs(heights, visited, i, j - 1, m, n);\n }\n if (j < n - 1 && !visited[i][j + 1] && heights[i][j + 1] >= heights[i][j]) {\n dfs(heights, visited, i, j + 1, m, n);\n }\n }\n};\n```\n\n\n\n# Please upvote the solution if you understood it.\n![1_3vhNKl1AW3wdbkTshO9ryQ.jpg](https://assets.leetcode.com/users/images/0161dd3b-ad9f-4cf6-8c43-49c2e670cc21_1699210823.334661.jpeg)\n
10
0
['Depth-First Search', 'Graph', 'Matrix', 'C++', 'Python3']
5
pacific-atlantic-water-flow
C++ Simple Readable Recursive DFS Solution
c-simple-readable-recursive-dfs-solution-6jas
We need to find cells that can reach Pacific and Atlantic.\nSo we keep a vector "states": 1 = can reach Pacific, 2 = can reach Atlantic, 3 = can reach both.\n\n
yehudisk
NORMAL
2021-03-25T09:19:56.637985+00:00
2021-03-25T09:19:56.638022+00:00
828
false
We need to find cells that can reach Pacific and Atlantic.\nSo we keep a vector "states": 1 = can reach Pacific, 2 = can reach Atlantic, 3 = can reach both.\n```\nclass Solution {\npublic:\n vector<vector<int>> pacificAtlantic(vector<vector<int>>& matrix) {\n if (!matrix.size() || !matrix[0].size()) \n return res;\n \n n = matrix.size();\n m = matrix[0].size();\n states.assign(n,vector<int> (m, 0));\n \n for (int i = 0; i < n; i++) {\n recDFS(matrix, i, 0, INT_MIN, 1);\n recDFS(matrix, i, m-1, INT_MIN, 2);\n }\n \n for (int i = 0; i < m; i++) {\n recDFS(matrix, 0, i, INT_MIN, 1);\n recDFS(matrix, n-1, i, INT_MIN, 2);\n }\n \n return res;\n }\n \nprivate:\n vector<vector<int>> res, states;\n vector<int> x_points = {1, 0, -1, 0};\n vector<int> y_points = {0, 1, 0, -1};\n int m, n;\n \n bool isValid(int x, int y) {\n return x < n and x >= 0 and y < m and y >= 0;\n }\n \n void recDFS(vector<vector<int>>& mat, int x, int y, int prev, int prev_state) {\n if (!isValid(x, y) || mat[x][y] < prev || states[x][y] == prev_state || states[x][y] == 3) \n return;\n \n states[x][y] += prev_state;\n \n if (states[x][y] == 3) \n res.push_back({x, y});\n \n for (int i = 0; i < 4; i++) {\n recDFS(mat, x + x_points[i], y + y_points[i], mat[x][y], prev_state);\n }\n }\n};\n```\n**Like it? please upvote!**
10
2
['C']
0
pacific-atlantic-water-flow
Java DFS Solution
java-dfs-solution-by-mugdhagovilkar1197-2mqp
\nclass Solution {\n boolean pacific;\n boolean atlantic;\n int numRows;\n int numColumns;\n public List<List<Integer>> pacificAtlantic(int[][] m
mugdhagovilkar1197
NORMAL
2019-10-19T03:12:32.721345+00:00
2019-10-19T03:12:32.721394+00:00
1,131
false
```\nclass Solution {\n boolean pacific;\n boolean atlantic;\n int numRows;\n int numColumns;\n public List<List<Integer>> pacificAtlantic(int[][] matrix) {\n //Go through all the cells in the matrix\n //Run a DFS for each cell\n //In the execution of the DFS, set pacific and atlantic to true or false\n //at the end of the execution, if both pacific and atlantic are true, then add i,j to the list\n \n //create a boolean visited matrix\n \n \n //create a list of answers;\n List<List<Integer>> answers = new ArrayList<List<Integer>>();\n if(matrix == null || matrix.length == 0 || matrix[0].length == 0)\n return answers;\n \n numRows = matrix.length;\n numColumns = matrix[0].length;\n \n \n for(int i = 0;i<matrix.length; i++)\n {\n for(int j = 0;j<matrix[0].length;j++)\n {\n pacific = false;\n atlantic = false;\n boolean[][] visited = new boolean[matrix.length][matrix[0].length];\n dfs(matrix,visited,i,j);\n if(pacific && atlantic)\n {\n ArrayList<Integer> temp = new ArrayList<Integer>();\n temp.add(i);\n temp.add(j);\n answers.add(temp);\n }\n }\n }\n return answers;\n \n \n \n }\n \n //In the execution of DFS,\n //once you set the value of pacific or atlantic to true, don\'t change it\n public void dfs(int[][] matrix, boolean[][] visited, int i, int j)\n { \n //mark the node as visited\n visited[i][j] = true;\n \n //check for pacific\n if(( ( (i==0) && (j>=0 && j<numColumns) ) || ( (j==0) && (i>=0 && i<numRows) ) ) && !pacific)\n {\n pacific = true; \n }\n \n \n //check for atlantic\n if(( ( (i==numRows-1) && (j>=0 && j<numColumns) ) || ( (j == numColumns-1) && (i>=0 && i<numRows) ) ) && !atlantic)\n {\n atlantic = true; \n }\n \n // if(i<0 || i>=numRows || y<0 || y>=numColumns )\n // return;\n \n int x = i;\n int y = j;\n //top is x-1,y\n if( (x-1)>=0 && y>=0 && y<numColumns && (matrix[x][y] >= matrix[x-1][y]) && !visited[x-1][y])\n dfs(matrix,visited,x-1,y);\n \n \n //right is x,y+1\n if( x>=0 && x<numRows && y+1<numColumns && (matrix[x][y] >= matrix[x][y+1]) && !visited[x][y+1] )\n dfs(matrix,visited,x,y+1);\n \n //bottom is x+1,y\n if(x+1<numRows && y>=0 && y<numColumns && (matrix[x][y] >= matrix[x+1][y]) && !visited[x+1][y])\n dfs(matrix,visited,x+1,y);\n \n //left is x,y-1\n if(x>=0 && x<numRows && y-1>=0 && matrix[x][y] >= matrix[x][y-1] && !visited[x][y-1])\n dfs(matrix,visited,x,y-1);\n \n \n }\n}\n```
10
0
[]
4
pacific-atlantic-water-flow
The driver for C# is broken
the-driver-for-c-is-broken-by-showmewhat-ix0m
All submissions would get\n\n\nLine 22: Char 16: error CS0266: Cannot implicitly convert type \'System.Collections.Generic.IList<int[]>\' to \'System.Collection
showmewhatyougot
NORMAL
2019-06-22T01:26:15.110873+00:00
2019-06-22T01:26:15.110944+00:00
1,229
false
All submissions would get\n\n```\nLine 22: Char 16: error CS0266: Cannot implicitly convert type \'System.Collections.Generic.IList<int[]>\' to \'System.Collections.Generic.IList<System.Collections.Generic.IList<int>>\'. An explicit conversion exists (are you missing a cast?) (in __Driver__.cs)\n```
10
0
[]
4
pacific-atlantic-water-flow
Why we reverse? Intuition from brute-force to optimized
why-we-reverse-intuition-from-brute-forc-9el8
Going through discussion tab and youtube folks found that a lot of people start an explanation like this:\n\n"Let us reverse logic in this problem."\n"It should
vokasik
NORMAL
2022-09-03T23:01:02.802500+00:00
2022-09-04T00:10:35.154126+00:00
407
false
Going through discussion tab and youtube folks found that a lot of people start an explanation like this:\n\n"Let us **reverse logic** in this problem."\n"It should be **obvious** from the start that we\'ll need to solve this problem **in reverse**."\n\nThose all are smart folks and for them "it\'s quite **obvious** what to do", but for me it was not and I had to scratch the back of my head a bit. I\'ll write down how I ended up with the same solution.\n\nThis is the first thing that came to my mind.\n\n**1. Brute-force**\n\nAs I want to find **the shortest path** to an ocean from a [row,col] cell I picked BFS graph traversal.\nAccording to the problem statement the water from the [row,col] cell should **end up in both Pacific and Atlantic** oceans. So we will need 2 sets to track this requirements.\n\nWe go from a "land" cell to out of boundaries `row < 0 or row > ROWS or col < 0 or col > COLS`\n\n**Observation #1**: The first observation that I got is that as soon as we reach a border cell (marked with pink on the pic) - we definitely end up in an ocean. Think about an ocean cell as the one with height = 0.\n\n**Observation #2**: Bottom-left and top-right land cells end up in both oceans. They have the same coordinates adjacent to both oceans\n\n![image](https://assets.leetcode.com/users/images/f016131b-80ab-41fa-b96e-a6938d7a3f5c_1662242543.9600108.png)\n\nI start a BFS traversal for every possible [row,col] combination and when I am on a "border cell" I store *traversal_starting_position* in a *reached_X_ocean* set. This is how I check a "border cell" position\n```\nif r == 0 or c == 0:\n reached_pacific_ocean.add(traversal_starting_position)\nif r == ROWS - 1 or c == COLS - 1:\n reached_atlantic_ocean.add(traversal_starting_position)\n```\n\nWhen I am done with the traversals I check which cells ended up in both oceans and return them.\n\nThis approach will work, but will be slow - `O(ROWS*COLS)^2)`\n\n![image](https://assets.leetcode.com/users/images/6105af16-7f4d-4ed8-adae-95659f95fc4e_1662234754.5888665.png)\n\nSource code for the approach:\n```\nclass Solution:\n def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:\n def bfs(traversal_starting_position):\n queue = deque([traversal_starting_position])\n visited = set()\n \n while queue:\n r,c = queue.popleft()\n \n if r == 0 or c == 0:\n\t\t\t\t reached_pacific_ocean.add(traversal_starting_position)\n if r == ROWS - 1 or c == COLS - 1:\n\t\t\t\t reached_atlantic_ocean.add(traversal_starting_position)\n \n if traversal_starting_position in reached_atlantic_ocean and traversal_starting_position in reached_pacific_ocean:\n return\n \n for dr,dc in [(1,0),(-1,0),(0,1),(0,-1)]:\n nr,nc = r + dr, c + dc\n \n if 0 <= nr < ROWS and 0 <= nc < COLS and heights[nr][nc] <= heights[r][c] \\\n and (nr,nc) not in visited:\n queue.append((nr,nc))\n visited.add((nr,nc))\n \n ROWS,COLS = len(heights), len(heights[0])\n \n reached_atlantic_ocean = set()\n reached_pacific_ocean = set()\n \n for traversal_starting_position in product(range(ROWS), range(COLS)):\n bfs(traversal_starting_position)\n \n return reached_atlantic_ocean & reached_pacific_ocean\n```\n\n**2. Optimizing brute-force**\n\nBy now we know a few things:\n* water flows top to bottom (physics 101)\n* If we got to a border cell, we are in the ocean\n* we used 2 sets to identify if a cell landed in both oceans\n* brute-forcing every [row.col] **is slow**\n\nLet\'s start from the last item from the list.\n\n**How can we speed it up?**\n\nIn order to speed it up we need to reduce number of *traversal_starting_position* checks, but how?\n\nLet\'s look at the example:\n\n```\n11112\n10001\n10401\n10001\n21111\n```\n\nIn our case no matter what we do, `4` will not reach any ocean. The same we can say about any of `0`. So it does not make any sence to check them. C\u0336r\u0336o\u0336s\u0336s\u0336i\u0336n\u0336g\u0336 \u0336o\u0336u\u0336t\u0336\n\n**How do we know which land cells can reach an ocean?**\n\nFrom the bruce-force approach\'s observation #1 and #2 we know that any border cell can reach an ocean and at least 2 border cells can reach both oceans.\n\nBased on the above information we need somehow to reach the border land cells. How?\n\nThe only 2 ways to reach a border cell:\n1) start from it \n2) **Observation #3**: arrive from a heigher (or equal) land cell adjacent to the border cell.\n\n![image](https://assets.leetcode.com/users/images/0b7e100f-4244-4c89-a2a8-3d6a561cc815_1662242903.9839532.png)\n\nIf we repeat the process again and again (looks like peeling an onion ring by ring) we will end up with land cells that we are stuck on and cannot go higher anymore.\n\nThis way we drop land cells that can\'t guide us to a possible solution as soon as possible.\n\n---\n\nThis is what we do in **Top-Down** approaches: you have your target (big goal) and you build a way to get there from smaller targets.\n\n---\n\nSo we need to track which land cells end up in which ocean and find intersecting coordinates in both atlantic and pacific sets and we are done.\n\n**How do we do it?**\n\nNow that we know what we need, left to figure out how to achive it.\n\n**1. We start from border cells**.\nWe split border cells in 2 groups: the ones that are adjacent to Pacific ocean and another one for Atlantic ocean. We need to know which border cell ended up in which ocean.\n\n**2. We start BFS traversion on those border cells**\nHow do we determine how to expand the BFS search space???\n\nOriginal state transition from the problem description:\n...*water can flow ... if the neighboring cell\'s height* \\*<=\\* *current cell\'s height..*\n\nBut we are going **from the bottom to the top**, so this needs to be **reversed** \n...*water can flow ... if the neighboring cell\'s height* \\*>=\\* *current cell\'s height..*\n\n**3. We got land cells that we cannot move heigher anymore**\nWe intersect such cells from both oceans and that\'s our result.\n\n**But it is still not optimized!!!**\n\nIn order to speed up the current approach we need somehow to run **in parallel** our BFS traversals for multiple starting coordinates. But good old BFS runs only sequentially for each starting point???\n\nLuckly for us there is (if you did not know, now you know) **multi-source BFS** (aka MS BFS, click [here](https://www.vldb.org/pvldb/vol8/p449-then.pdf) if you like papers).\n\nEach time you see that you need to **run BFS on MULTIPLE SOURCES at the SAME TIME** - it\'s 99.99% MS BFS (the other 0.01 is DP, but that\'s another problem). The same one is used in "Rotting Oranges" (amazon\'s fav), "Map of Highest Peak", "As Far from Land as Possible", "Pacific Atlantic Water Flow", "Wall and Gates" and others.\n\n---\n\nMore about similar problems and how to apply it I posted for another problem [here](https://leetcode.com/problems/as-far-from-land-as-possible/discuss/2515617/how-to-solve-multi-source-bfs-problems-intuition)\n\n---\n\nNow left to apply MS BFS to our problem and we are done.\n\n**Optimization with MS BFS**\n\nAs we need to start **in parallel** we need to prepare our "BFS queue" with the border land cells (sources) in advance. So we have to find all the border land cells and place them in the queue before staring the typical "BFS loop". This way we traverse multiple starting points **in parallel**.\n\nI like the idea of a "virtual start node" aka dummy on the pic: You virtually connect all the "land" cells to a virtual node and then do a classic BFS on the virtual node. Except this is the mental model. In the code you just find the "starting" source nodes and dump them in the queue and run a bfs on the queue.\n\n![image](https://assets.leetcode.com/users/images/4e361cdd-25d6-4bf7-8f1a-670a119ca8d3_1662245696.096896.png)\n*The pic as always taken from the Internet.*\n\nAs a result of running 2 BFS for both oceans we are going to have 2 **visited** sets, that contain all "reachable" land cells from border cells. We intersect the cell coordinates and return them.\n\n---\n\nSo, hopefully, by now we know why we need to **reverse the logic** and why it\'s **obvious**.\nThis is the same problem with solutions that provide tabular DP. You got 5 lines of code and no idea how they ended up there.\n\n---\n\nSource code for the approach:\n```\nclass Solution:\n def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:\n def bfs(queue):\n visited = set(queue)\n while queue:\n r,c = queue.popleft()\n \n for dr,dc in [(1,0),(-1,0),(0,1),(0,-1)]:\n nr,nc = r + dr, c + dc\n \n if 0 <= nr < ROWS and 0 <= nc < COLS and \\\n heights[r][c] <= heights[nr][nc] and (nr,nc) not in visited:\n visited.add((nr,nc))\n queue.append((nr,nc))\n \n return visited\n \n atlantic_ocean_queue = deque()\n pacific_ocean_queue = deque()\n \n ROWS,COLS = len(heights),len(heights[0])\n \n for r in range(ROWS):\n atlantic_ocean_queue.append((r, COLS - 1))\n pacific_ocean_queue.append((r, 0))\n \n for c in range(COLS):\n atlantic_ocean_queue.append((ROWS - 1, c))\n pacific_ocean_queue.append((0, c))\n \n reached_atlantic_ocean = bfs(atlantic_ocean_queue)\n reached_pacific_ocean = bfs(pacific_ocean_queue)\n \n return reached_atlantic_ocean & reached_pacific_ocean\n```\n\nTC: `O(ROWS*COLS)`\nSC: `O(ROWS*COLS)`\n\nIt can also be solved with DFS. The same core logic, different traversal, recursion (stack) and ...\n\n... did you know that you can optimize/solve the problem with DP? \n\n( \u25D1\u203F\u25D1)\u0254\u250F\uD83C\uDF5F--\uD83C\uDF54\u2511\u0669(^\u25E1^ )\n\n**If you liked the read, upvote so the other people can see it too.**
9
0
['Python']
2
pacific-atlantic-water-flow
JavaScript DFS
javascript-dfs-by-ryan_barrett-m5mc
\n/**\n * @param {number[][]} matrix\n * @return {number[][]}\n */\nconst pacificAtlantic = (matrix) => {\n if (matrix.length === 0) return [];\n \n const pa
ryan_barrett
NORMAL
2020-04-20T19:24:11.758104+00:00
2020-04-20T19:24:42.830286+00:00
1,685
false
```\n/**\n * @param {number[][]} matrix\n * @return {number[][]}\n */\nconst pacificAtlantic = (matrix) => {\n if (matrix.length === 0) return [];\n \n const pacific = [];\n const atlantic = [];\n const result = [];\n \n for (let i = 0; i < matrix.length; i++) {\n pacific[i] = Array(matrix[0].length).fill(0);\n atlantic[i] = Array(matrix[0].length).fill(0);\n }\n \n // top and botom\n for (let i = 0; i < matrix[0].length; i++) {\n dfs(matrix, 0, i, Number.MIN_SAFE_INTEGER, pacific);\n dfs(matrix, matrix.length - 1, i, Number.MIN_SAFE_INTEGER, atlantic);\n }\n \n // left and right\n for (let i = 0; i < matrix.length; i++) {\n dfs(matrix, i, 0, Number.MIN_SAFE_INTEGER, pacific);\n dfs(matrix, i, matrix[0].length - 1, Number.MIN_SAFE_INTEGER, atlantic);\n }\n \n for (let i = 0; i < matrix.length; i++) {\n for (let j = 0; j < matrix[0].length; j++) {\n if (pacific[i][j] === 1 && atlantic[i][j] === 1) {\n result.push([i, j]);\n }\n }\n }\n \n return result;\n};\n\nfunction dfs(matrix, row, col, previous, ocean) {\n // if we\'re looking at a valid matrix position\n if (!isValid(matrix, row, col)) return;\n \n // ocean can\'t reach\n if (matrix[row][col] < previous) return;\n\n // the ocean was already here\n if (ocean[row][col] === 1) return;\n \n ocean[row][col] = 1;\n dfs(matrix, row + 1, col, matrix[row][col], ocean);\n dfs(matrix, row - 1, col, matrix[row][col], ocean);\n dfs(matrix, row, col + 1, matrix[row][col], ocean);\n dfs(matrix, row, col - 1, matrix[row][col], ocean);\n}\n\nfunction isValid(matrix, row, col) {\n const rowIsValid = row >= 0 && row < matrix.length;\n const colIsValid = col >= 0 && col < matrix[0].length;\n return rowIsValid && colIsValid;\n}\n```
9
1
['Depth-First Search', 'JavaScript']
0
pacific-atlantic-water-flow
[LeetCode The Hard Way] Easy DFS with Explanations
leetcode-the-hard-way-easy-dfs-with-expl-8a73
Please check out LeetCode The Hard Way for more solution explanations and tutorials. If you like it, please give a star and watch my Github Repository.\n\n---\n
__wkw__
NORMAL
2022-08-31T02:53:55.415835+00:00
2022-08-31T03:01:31.770330+00:00
1,821
false
Please check out [LeetCode The Hard Way](https://wingkwong.github.io/leetcode-the-hard-way/) for more solution explanations and tutorials. If you like it, please give a star and watch my [Github Repository](https://github.com/wingkwong/leetcode-the-hard-way).\n\n---\n\n```cpp\n// https://wingkwong.github.io/leetcode-the-hard-way/solutions/0400-0499/pacific-atlantic-water-flow-medium\nclass Solution {\npublic:\n void dfs(vector<vector<int>>& M, vector<vector<int>>& vis, int i, int j) {\n int m = M.size(), n = M[0].size();\n // marked this cell (i, j) as visited\n // so that we won\'t visit it again\n vis[i][j] = 1;\n // perform DFS on the left cell\n if (i - 1 >= 0 && !vis[i - 1][j] && M[i - 1][j] >= M[i][j]) dfs(M, vis, i - 1, j);\n // perform DFS on the right cell\n if (i + 1 < m && !vis[i + 1][j] && M[i + 1][j] >= M[i][j]) dfs(M, vis, i + 1, j);\n // perform DFS on the top cell\n if (j - 1 >= 0 && !vis[i][j - 1] && M[i][j - 1] >= M[i][j]) dfs(M, vis, i, j - 1);\n // perform DFS on the bottom cell\n if (j + 1 < n && !vis[i][j + 1] && M[i][j + 1] >= M[i][j]) dfs(M, vis, i, j + 1);\n }\n \n vector<vector<int>> pacificAtlantic(vector<vector<int>>& M) {\n vector<vector<int>> ans;\n int m = M.size(), n = M[0].size();\n // P[i][j] = 1 means it is able to flow to pacific ocean\n vector<vector<int>> P(m, vector<int>(n));\n // A[i][j] = 1 means it is able to flow to atlantic ocean\n vector<vector<int>> A(m, vector<int>(n));\n for(int i = 0; i < m; i++) {\n // perform dfs starting from the left-most column \n dfs(M, P, i, 0);\n // perform dfs starting from the right-most column \n dfs(M, A, i, n - 1);\n }\n for(int i = 0; i < n; i++) {\n // perform dfs starting from the top-most row\n dfs(M, P, 0, i);\n // perform dfs starting from the bottom-most row\n dfs(M, A, m - 1, i);\n }\n // iterate each row\n for(int i = 0; i < m; i++) {\n // iterate each column\n for(int j = 0; j < n; j++) {\n // if both P[i][j] & A[i][j] are visited\n // that means this cell can flow to both ocean\n if(P[i][j] && A[i][j]) {\n // then put the coordinate (i, j) to answer\n ans.push_back(vector<int>{i, j});\n }\n }\n }\n return ans;\n }\n};\n```
8
0
['Depth-First Search', 'C', 'C++']
3
pacific-atlantic-water-flow
🗓️ Daily LeetCoding Challenge August, Day 31
daily-leetcoding-challenge-august-day-31-78qi
This problem is the Daily LeetCoding Challenge for August, Day 31. Feel free to share anything related to this problem here! You can ask questions, discuss what
leetcode
OFFICIAL
2022-08-31T00:00:07.309907+00:00
2022-08-31T00:00:07.309948+00:00
4,584
false
This problem is the Daily LeetCoding Challenge for August, Day 31. Feel free to share anything related to this problem here! You can ask questions, discuss what you've learned from this problem, or show off how many days of streak you've made! --- If you'd like to share a detailed solution to the problem, please create a new post in the discuss section and provide - **Detailed Explanations**: Describe the algorithm you used to solve this problem. Include any insights you used to solve this problem. - **Images** that help explain the algorithm. - **Language and Code** you used to pass the problem. - **Time and Space complexity analysis**. --- **📌 Do you want to learn the problem thoroughly?** Read [**⭐ LeetCode Official Solution⭐**](https://leetcode.com/problems/pacific-atlantic-water-flow/solution) to learn the 3 approaches to the problem with detailed explanations to the algorithms, codes, and complexity analysis. <details> <summary> Spoiler Alert! We'll explain these 2 approaches in the official solution</summary> **Approach 1:** Breadth First Search (BFS) **Approach 2:** Depth First Search (DFS) </details> If you're new to Daily LeetCoding Challenge, [**check out this post**](https://leetcode.com/discuss/general-discussion/655704/)! --- <br> <p align="center"> <a href="https://leetcode.com/subscribe/?ref=ex_dc" target="_blank"> <img src="https://assets.leetcode.com/static_assets/marketing/daily_leetcoding_banner.png" width="560px" /> </a> </p> <br>
8
0
[]
32
pacific-atlantic-water-flow
Explanation for why DP doesn't work with code
explanation-for-why-dp-doesnt-work-with-89a70
\nclass Solution:\n def __init__(self):\n self.PACIFIC, self.ATLANTIC = 0, 1\n self.VISITED = -1\n EAST, WEST = [0, 1], [0, -1]\n
jaksparro
NORMAL
2022-01-12T00:45:12.237741+00:00
2022-01-12T01:39:41.069824+00:00
504
false
```\nclass Solution:\n def __init__(self):\n self.PACIFIC, self.ATLANTIC = 0, 1\n self.VISITED = -1\n EAST, WEST = [0, 1], [0, -1]\n NORTH, SOUTH = [-1, 0], [1, 0]\n self.DIRECTIONS = [EAST, WEST, NORTH, SOUTH]\n self.ROWS, self.COLS = 0, 0\n self.heights = []\n self.pacific_map = {}\n self.atlantic_map = {}\n \n \n def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:\n self.ROWS, self.COLS = len(heights), len(heights[0])\n self.heights = heights\n both_reachable_coordinates = []\n \n for row in range(self.ROWS):\n for col in range(self.COLS):\n if (self.ocean_reachable(row, col, self.ATLANTIC) and\n self.ocean_reachable(row, col, self.PACIFIC)):\n both_reachable_coordinates.append([row, col])\n\n return both_reachable_coordinates\n \n def in_pacific(self, row, col):\n return row == -1 or col == -1\n \n def in_atlantic(self, row, col):\n return row == self.ROWS or col == self.COLS\n \n def in_range(self, row, col):\n return row in range(self.ROWS) and col in range(self.COLS)\n \n def can_water_flow(self, curr_height, new_row, new_col):\n return curr_height >= self.heights[new_row][new_col]\n \n def not_visited(self, row, col):\n return self.heights[row][col] != -1\n \n def update_dp_map(self, ocean, row, col, value):\n if ocean == self.PACIFIC:\n self.pacific_map[(row,col)] = value\n else:\n self.atlantic_map[(row,col)] = value \n\n def is_cached(self, row, col, ocean):\n if ocean == self.PACIFIC:\n return (row,col) in self.pacific_map\n else:\n return (row,col) in self.atlantic_map\n \n def cached_value(self, row, col, ocean):\n if ocean == self.PACIFIC:\n return self.pacific_map[(row,col)]\n else:\n return self.atlantic_map[(row,col)]\n\n def ocean_reachable(self, row, col, ocean):\n if self.is_cached(row, col, ocean):\n return self.cached_value(row, col, ocean)\n \n if ocean == self.PACIFIC and self.in_pacific(row, col):\n self.update_dp_map(ocean, row, col, True)\n return True\n if ocean == self.ATLANTIC and self.in_atlantic(row, col):\n self.update_dp_map(ocean, row, col, True)\n return True\n \n if not self.in_range(row, col):\n self.update_dp_map(ocean, row, col, False)\n return False\n \n curr_height = self.heights[row][col]\n self.heights[row][col] = self.VISITED\n for drow, dcol in self.DIRECTIONS:\n new_row, new_col = row + drow, col + dcol\n if ((((self.in_range(new_row, new_col) and \n self.not_visited(new_row, new_col) and \n self.can_water_flow(curr_height, new_row, new_col)) or\n not self.in_range(new_row, new_col)) and\n self.ocean_reachable(new_row, new_col, ocean))):\n self.heights[row][col] = curr_height\n self.update_dp_map(ocean, row, col, True) \n self.update_dp_map(ocean, new_row, new_col, True) \n return True\n \n self.heights[row][col] = curr_height\n self.update_dp_map(ocean, row, col, False)\n return False\n```\n\n![image](https://assets.leetcode.com/users/images/a0a1979b-ab69-40cc-9f6d-61d122d0a7f2_1641948104.655987.png)\n\nLets say you are trying to find if you can reach Pacific from index(1,2), and you reached index(1,2) via index(1,1). Also, lets assume the only way to Pacific from index(1,2) is via index(1,1), but since we reached index(1,2) from (1,1), we cannot visit it again to prevent cycles. So, even though the we can reach pacific from (1,2), since the answer to (1,2) was dependent on (1,1) and the answer to (1,1) was dependent on (1,2), we have what we call a **Cyclic Dependency**. Because of this, DP will not work for certain cases like this.
8
0
['Dynamic Programming']
3
pacific-atlantic-water-flow
Pacific Atlantic Water Flow | Easy solution | simple code using DFS
pacific-atlantic-water-flow-easy-solutio-dy3b
The idea is we are visiting every index that is reachable from pacific and atlantic and marking it as visited=true , and Finally we are checking if any index is
srinivasteja18
NORMAL
2021-03-25T08:58:01.154957+00:00
2021-03-25T09:01:09.540325+00:00
303
false
The idea is we are visiting every index that is reachable from pacific and atlantic and marking it as `visited=true` , and Finally we are checking if any index is reachable from both pacific and atlantic,then it is pushed into `res`.\n\n**DO UPVOTE** if you find it helpful!!\n```\nclass Solution {\npublic:\n vector<vector<int>> pacificAtlantic(vector<vector<int>>& mat) {\n vector<vector<int>>res;\n int n = mat.size();\n if(n==0) return res;\n int m = mat[0].size();\n if(m==0) return res;\n vector<vector<bool>>pc(n,vector<bool>(m,false));\n vector<vector<bool>>at(n,vector<bool>(m,false));\n \n for(int i=0;i<n;i++){\n dfs(mat,pc,i,0,INT_MIN);\n dfs(mat,at,i,m-1,INT_MIN);\n }\n for(int j=0;j<m;j++){\n dfs(mat,pc,0,j,INT_MIN);\n dfs(mat,at,n-1,j,INT_MIN);\n }\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(pc[i][j] && at[i][j])\n res.push_back({i,j});\n }\n }\n return res;\n } \n void dfs(vector<vector<int>>&mat,vector<vector<bool>> &visited,int i,int j,int prev){\n if(i<0 || j<0 || i>=mat.size() || j>= mat[0].size() || visited[i][j] || mat[i][j]<prev) return;\n visited[i][j] = true;\n dfs(mat,visited,i+1,j,mat[i][j]);\n dfs(mat,visited,i-1,j,mat[i][j]);\n dfs(mat,visited,i,j+1,mat[i][j]);\n dfs(mat,visited,i,j-1,mat[i][j]);\n }\n};\n```\n
8
4
[]
0
pacific-atlantic-water-flow
Most Concise C++ Solution (DFS + Bit Mask)
most-concise-c-solution-dfs-bit-mask-by-ntoj1
\nclass Solution {\npublic:\n\tint dx[4] = {1, -1, 0, 0};\n\tint dy[4] = {0, 0, -1, 1};\n\n\tvector<vector<int>> ans, mask;\n\n\tvector<vector<int>> pacificAtla
jigyansunanda
NORMAL
2022-08-31T09:28:57.620199+00:00
2022-08-31T09:28:57.620245+00:00
999
false
```\nclass Solution {\npublic:\n\tint dx[4] = {1, -1, 0, 0};\n\tint dy[4] = {0, 0, -1, 1};\n\n\tvector<vector<int>> ans, mask;\n\n\tvector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {\n\t\tint m = heights.size(), n = heights[0].size();\n\t\tmask.resize(m, vector<int>(n, 0));\n\n\t\tfunction<void(int, int, int, int)> dfs = [&](int r, int c, int prev, int val) {\n\t\t\tif (r < 0 or c < 0 or r >= m or c >= n or ((mask[r][c] | val) == mask[r][c])) return;\n\t\t\tif (heights[r][c] < prev) return;\n\t\t\tmask[r][c] |= val;\n\t\t\tif (mask[r][c] == 3) ans.push_back({r, c});\n\t\t\tfor (int dir = 0; dir < 4; ++dir) {\n\t\t\t\tint x = r + dx[dir];\n\t\t\t\tint y = c + dy[dir];\n\t\t\t\tdfs(x, y, heights[r][c], mask[r][c]);\n\t\t\t}\n\t\t};\n\n\t\tfor (int i = 0; i < m; ++i) {\n\t\t\tdfs(i, 0, INT_MIN, 1);\n\t\t\tdfs(i, n - 1, INT_MIN, 2);\n\t\t}\n\t\tfor (int j = 0; j < n; ++j) {\n\t\t\tdfs(0, j, INT_MIN, 1);\n\t\t\tdfs(m - 1, j, INT_MIN, 2);\n\t\t}\n\t\treturn ans;\n\t}\n};\n```
7
0
['Depth-First Search', 'C', 'Bitmask']
0
pacific-atlantic-water-flow
Think the other way! 💡 Ocean to Land DFS ✅ [C++] || Explaind 🔥
think-the-other-way-ocean-to-land-dfs-c-l9kmx
Intution \uD83D\uDCA1\ninstead of going from land to ocean\nwe will do a DFS from both the oceans towards the land\nif the cell of the land can be visited from
dcoder_op
NORMAL
2022-08-23T10:40:54.475546+00:00
2022-08-23T10:40:54.475585+00:00
788
false
## **Intution** \uD83D\uDCA1\ninstead of going from land to ocean\nwe will do a *DFS* from **both the oceans** towards the land\nif the cell of the land can be visited from both oceans, vice-versa of that (that is asked in question) is also **true**\n```\nclass Solution {\nprivate:\n void dfs(vector<vector<int>>& land, vector<vector<bool>> &oceanToLand, int i, int j, int rows, int cols) {\n if(i < 0 || i >= rows || j < 0 || j >= cols || oceanToLand[i][j] == true)\n return;\n \n oceanToLand[i][j] = true; // marking visited, means ocean water can come to that land\n \n // just checking the neighbouring cells\n if(i + 1 < rows && land[i + 1][j] >= land[i][j])\n dfs(land, oceanToLand, i + 1, j, rows, cols);\n \n if(i - 1 >= 0 && land[i - 1][j] >= land[i][j])\n dfs(land, oceanToLand, i - 1, j, rows, cols);\n \n if(j + 1 < cols && land[i][j + 1] >= land[i][j])\n dfs(land, oceanToLand, i, j + 1, rows, cols);\n \n if(j - 1 >= 0 && land[i][j - 1] >= land[i][j])\n dfs(land, oceanToLand, i, j - 1, rows, cols);\n }\n\npublic:\n vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {\n \n vector<vector<int>> ans;\n \n int rows = heights.size();\n int cols = heights[0].size();\n \n vector<vector<bool>> pacificToLand(rows, vector<bool>(cols, false));\n vector<vector<bool>> atlanticToLand(rows, vector<bool>(cols, false));\n \n // column 0 is pacific ocean\'s boundary and last column (cols - 1) is atlantic\'s\n for(int i = 0; i < rows; ++i) {\n dfs(heights, pacificToLand, i, 0, rows, cols);\n dfs(heights, atlanticToLand, i, cols - 1, rows, cols);\n }\n \n // row 0 is pacific ocean\'s boundary and last row (rows - 1) is atlantic\'s\n for(int i = 0; i < cols; ++i) {\n dfs(heights, pacificToLand, 0, i, rows, cols);\n dfs(heights, atlanticToLand, rows - 1, i, rows, cols);\n }\n \n \n // if from *both* oceans, we can reach to a particular cell of land, then vice-versa is also true\n for(int i = 0; i < rows; ++i) {\n for(int j = 0; j < cols; ++j) {\n if(pacificToLand[i][j] && atlanticToLand[i][j]) {\n ans.push_back({i, j});\n }\n }\n }\n return ans;\n }\n};\n```\nIf you have any doubts, *Please ask in the Comments* \nIf it helped you, **Please UpVote** \uD83D\uDD3C :)
7
0
['Depth-First Search', 'Graph', 'C', 'C++']
2