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
reconstruct-a-2-row-binary-matrix
Efficient Python solution
efficient-python-solution-by-aquaman97-3idj
python\nclass Solution:\n def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]:\n if upper + lower != sum(colsum)
Aquaman97
NORMAL
2019-11-10T14:59:15.202553+00:00
2019-11-10T14:59:15.202587+00:00
114
false
```python\nclass Solution:\n def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]:\n if upper + lower != sum(colsum):\n return []\n n = len(colsum)\n res = [[0]*n for _ in range(2)]\n c_2 = 0\n for i in range(n):\n if colsum[i] == 2:\n res[0][i], res[1][i] = 1, 1\n c_2 += 1\n \n if c_2 > upper or c_2 > lower:\n return []\n \n u, l = upper-c_2, lower-c_2\n \n for i in range(n):\n if colsum[i] == 1:\n if u > 0:\n res[0][i] = 1\n u -= 1\n elif l > 0:\n res[1][i] = 1\n l -= 1\n \n return res\n```
1
0
[]
0
reconstruct-a-2-row-binary-matrix
[Python3] straightforward
python3-straightforward-by-cenkay-qsjq
\nclass Solution:\n def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]:\n res = [[0] * len(colsum) for _ in ran
cenkay
NORMAL
2019-11-10T08:37:10.729512+00:00
2019-11-10T08:37:10.729546+00:00
57
false
```\nclass Solution:\n def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]:\n res = [[0] * len(colsum) for _ in range(2)]\n for j, sm in enumerate(colsum):\n if sm == 2:\n if upper == 0 or lower == 0:\n return []\n upper -= 1\n lower -= 1\n res[0][j] = res[1][j] = 1\n elif sm:\n if upper == lower == 0:\n return []\n if upper >= lower:\n upper -= 1\n res[0][j] = 1\n else:\n lower -= 1\n res[1][j] = 1\n return res if upper == lower == 0 else []\n```
1
1
[]
0
reconstruct-a-2-row-binary-matrix
Understandable and concise code in C++
understandable-and-concise-code-in-c-by-4uir3
Probably, you have already checked other solutions from the discussions and got the idea that this problem can be solved using a greedy approach.\nHere is one o
leetcodekz
NORMAL
2019-11-10T06:53:08.551351+00:00
2019-11-10T06:53:18.612346+00:00
90
false
Probably, you have already checked other solutions from the discussions and got the idea that this problem can be solved using a greedy approach.\nHere is one of the variations of implementing it. \n```c++\nclass Solution {\npublic:\n vector<vector<int>> reconstructMatrix(int upper, int lower, vector<int>& colsum) {\n if (accumulate(begin(colsum), end(colsum), 0) != upper + lower) return vector<vector<int>>{};\n vector<vector<int>> res(2, vector<int>(colsum.size(), 0));\n fillRow(0, upper, colsum, res);\n fillRow(1, lower, colsum, res);\n return res;\n }\nprivate:\n void fillRow(int index, int values, vector<int>& colsum, vector<vector<int>>& res) {\n for (int i = 0; i < colsum.size(); i++) {\n int temp = min(colsum[i], values);\n res[index][i] = temp;\n colsum[i] -= temp;\n values -= temp;\n }\n }\n};\n```
1
0
['Greedy']
0
reconstruct-a-2-row-binary-matrix
Simple C++ solution (fills up colsum[i]=2 first and then colsum[i]=1) with explanation
simple-c-solution-fills-up-colsumi2-firs-35lp
fills up the columns with colsum[i]=2 first with the first for loop\n-> once when "1" is filled up in upper/lower row, upper/lower should be decreased by 1 \n2.
eminem18753
NORMAL
2019-11-10T04:43:11.261884+00:00
2019-11-10T04:49:24.338054+00:00
69
false
1. fills up the columns with colsum[i]=2 first with the first for loop\n-> once when "1" is filled up in upper/lower row, upper/lower should be decreased by 1 \n2. if colsum[i]==1 and upper>0, fills up the upper row of the column with colsum[i]=1\n3. else if colsum[i]==1 and lower>0, fills up the lower row of the column with colsum[i]=1\n4. else if colsum[i]==1, return an empty array\n5. after the for loop, if upper or lower is not 0, return an empty array (because upper+lower is greater than sum(colsum[:])) \n```\nclass Solution \n{\n public:\n vector<vector<int>> reconstructMatrix(int upper, int lower, vector<int>& colsum) \n {\n int n=colsum.size();\n vector<vector<int>> result(2,vector<int>(n,0));\n for(int i=0;i<n;i++)\n {\n if(colsum[i]==2)\n {\n result[0][i]=1;\n result[1][i]=1;\n upper--;\n lower--;\n }\n }\n for(int i=0;i<n;i++)\n if(colsum[i]==1&&upper>0) result[0][i]=1, upper--;\n else if(colsum[i]==1&&lower>0) result[1][i]=1, lower--;\n else if(colsum[i]==1||upper<0||lower<0) return vector<vector<int>>(0,vector<int>(0,0)); \n\n if(upper!=0||lower!=0) return vector<vector<int>>(0,vector<int>(0,0)); \n return result;\n }\n};\n```
1
0
[]
0
reconstruct-a-2-row-binary-matrix
python greedy
python-greedy-by-hong_tao-kuxe
idea: fill columns of sum 2 first, then 1.\n\n def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]:\n if sum(col
hong_tao
NORMAL
2019-11-10T04:39:16.019894+00:00
2019-11-10T04:39:16.019970+00:00
145
false
idea: fill columns of sum 2 first, then 1.\n```\n def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]:\n if sum(colsum) != upper + lower:\n return []\n COL = len(colsum)\n res = [[0] * COL for _ in range(2)]\n \n for i in range(COL):\n if colsum[i] == 2:\n upper -= 1\n lower -= 1\n res[0][i] = res[1][i] = 1\n for i in range(COL):\n if colsum[i] == 1:\n if upper:\n upper -= 1\n res[0][i] = 1\n else:\n lower -= 1\n res[1][i] = 1\n return res if upper == 0 and lower == 0 else []\n```
1
1
['Python3']
0
reconstruct-a-2-row-binary-matrix
[Python] Greedy Solution
python-greedy-solution-by-cmh159-9vsf
\nclass Solution:\n def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]:\n res = [[0]*len(colsum),[0]*len(colsum
cmh159
NORMAL
2019-11-10T04:17:56.796591+00:00
2019-11-10T04:17:56.796642+00:00
82
false
```\nclass Solution:\n def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]:\n res = [[0]*len(colsum),[0]*len(colsum)]\n \n for i in range(len(colsum)):\n if colsum[i] <= upper:\n res[0][i] = colsum[i]\n upper -= colsum[i]\n colsum[i] = 0\n \n elif colsum[i] <= upper+lower:\n res[0][i] = upper\n colsum[i] -= upper\n upper = 0\n \n res[1][i] = colsum[i]\n lower -= colsum[i]\n colsum[i] = 0\n \n else:\n return []\n \n return res if upper+lower == 0 else []\n```
1
1
[]
0
reconstruct-a-2-row-binary-matrix
python simple and fast O(n)
python-simple-and-fast-on-by-aithanet-jtc3
\nclass Solution:\n def reconstructMatrix(self, upper, lower, colsum):\n if upper + lower != sum(colsum):\n return []\n N = len(cols
aithanet
NORMAL
2019-11-10T04:16:28.147607+00:00
2019-11-10T04:16:28.147651+00:00
95
false
```\nclass Solution:\n def reconstructMatrix(self, upper, lower, colsum):\n if upper + lower != sum(colsum):\n return []\n N = len(colsum)\n \n num_two = colsum.count(2)\n if num_two > lower or num_two > upper:\n return []\n \n res = [[0 for _ in range(N)] for _ in range(2)]\n \n for idx in range(N):\n if colsum[idx] == 0:\n continue\n elif colsum[idx] == 2:\n res[0][idx] = res[1][idx] = 1\n upper -= 1\n lower -= 1\n elif upper >= lower:\n res[0][idx] = 1\n upper -= 1\n else :\n res[1][idx] = 1\n lower -= 1\n\n return res\n```
1
1
['Python']
0
reconstruct-a-2-row-binary-matrix
python fast (100%) memory (100%) solution (19.Nov.09)
python-fast-100-memory-100-solution-19no-ggey
\nclass Solution:\n def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]:\n \n matrix = [[ 0 for i in rang
bixing
NORMAL
2019-11-10T04:10:12.690998+00:00
2019-11-10T04:13:29.474998+00:00
80
false
```\nclass Solution:\n def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]:\n \n matrix = [[ 0 for i in range(len(colsum))] for j in range(2)]\n \n matsum = sum(colsum)\n \n if matsum != upper+lower:\n return []\n \n colsum_counter = {}\n for i in range(3):\n colsum_counter[i] = 0\n \n for i in colsum:\n colsum_counter[i] +=1\n \n upper_counter = upper - colsum_counter[2]\n lower_counter = lower - colsum_counter[2]\n \n \n for col in range(len(colsum)):\n if colsum[col] == 2:\n matrix[0][col]=1\n matrix[1][col]=1\n elif colsum[col] ==0:\n continue\n else:\n if upper_counter>0:\n matrix[0][col]=1\n matrix[1][col]=0\n upper_counter-=1\n else:\n matrix[0][col]=0\n matrix[1][col]=1\n lower_counter -=1\n if lower_counter != 0:\n return []\n \n return matrix\n```
1
1
[]
0
reconstruct-a-2-row-binary-matrix
[C++] Solution with explanations
c-solution-with-explanations-by-orangeze-i89n
From colsum, we have several observations\n\t 0 can be ignored since both values in that column must be 0.\n\t 2 can also be ignored since both values in that c
orangezeit
NORMAL
2019-11-10T04:03:31.389898+00:00
2019-11-10T04:23:11.592345+00:00
133
false
* From ```colsum```, we have several observations\n\t* ```0``` can be ignored since both values in that column must be 0.\n\t* ```2``` can also be ignored since both values in that column must be 1.\n\t\t* Thus, we decrease both ```upper``` and ```lower``` by 1 and move on.\n\t* We only care about ```1```.\n* If ```upper``` or ```lower``` is negative, we cannot construct.\n* If the sum of ```upper``` and ```lower``` is not equal to the number of 1, we cannot construct.\n* Otherwise, we can.\n\n```\nclass Solution {\npublic:\n vector<vector<int>> reconstructMatrix(int upper, int lower, vector<int>& colsum) {\n int ones(0);\n for (const int& col: colsum)\n if (col == 2) {\n if ((--upper) < 0 || (--lower) < 0) return {};\n } else if (col == 1) {\n ones++;\n }\n \n if (upper + lower != ones) return {};\n \n vector<vector<int>> ans(2, vector<int>(colsum.size()));\n \n for (int i = 0; i < colsum.size(); ++i)\n if (colsum[i] == 2)\n ans[0][i] = ans[1][i] = 1;\n else if (colsum[i] == 1)\n (upper > 0 && upper--) ? ans[0][i] = 1 : ans[1][i] = 1;\n \n return ans;\n }\n};\n```
1
1
['Greedy']
0
reconstruct-a-2-row-binary-matrix
Greedy Constraint Resolution | Dart Solution | Time O(n) | Space O(n)
greedy-constraint-resolution-dart-soluti-y7me
ApproachThe solution uses a greedy approach to reconstruct a valid binary matrix: Two-Pass Construction: First pass: Handle fixed-value columns (sums of 0 and
user4343mG
NORMAL
2025-03-19T08:00:21.737952+00:00
2025-03-19T08:00:21.737952+00:00
2
false
## Approach The solution uses a greedy approach to reconstruct a valid binary matrix: 1. **Two-Pass Construction**: - First pass: Handle fixed-value columns (sums of 0 and 2) - Second pass: Distribute remaining 1s to satisfy row constraints 2. **Priority Assignment**: - For columns with sum=2: Place 1 in both rows - For columns with sum=0: Place 0 in both rows - For columns with sum=1: Prioritize first row until upper is satisfied, then second row 3. **Constraint Validation**: - Track remaining required 1s for each row (upper/lower counters) - Immediately return empty array when constraints cannot be met - Verify complete utilization (upper=lower=0) at the end This greedy approach works because columns with sum 2 and 0 have only one valid configuration, while columns with sum 1 provide flexibility to satisfy row constraints. ## Complexity - **Time Complexity**: $$O(n)$$ - Two passes through array of length n - Constant time operations per element - **Space Complexity**: $$O(n)$$ - Output matrix requires 2×n space - No additional significant data structures # Code ```dart [] class Solution { List<List<int>> reconstructMatrix(int upper, int lower, List<int> colsum) { List<int> firstRow = List.filled(colsum.length, -1); List<int> secondRow = List.filled(colsum.length, -1); for (var i = 0; i < colsum.length; i++) { if (colsum[i] == 2 && upper > 0 && lower > 0) { firstRow[i] = 1; secondRow[i] = 1; upper--; lower--; } else if (colsum[i] == 0) { firstRow[i] = 0; secondRow[i] = 0; } else if (colsum[i] == 2) { return []; } } for (var i = 0; i < colsum.length; i++) { if (colsum[i] == 1 && upper > 0) { firstRow[i] = 1; secondRow[i] = 0; upper--; } else if (colsum[i] == 1 && lower > 0) { firstRow[i] = 0; secondRow[i] = 1; lower--; } else if (colsum[i] == 1) { return []; } } if (upper == 0 && lower == 0) { return [firstRow, secondRow]; } else { return []; } } } ```
0
0
['Array', 'Greedy', 'Matrix', 'Dart']
0
reconstruct-a-2-row-binary-matrix
Intuitive Java Solution
intuitive-java-solution-by-taehyunkim023-5ej4
Code
taehyunkim023
NORMAL
2025-03-13T12:16:10.615247+00:00
2025-03-13T12:16:10.615247+00:00
8
false
# Code ```java [] import static java.lang.System.in; class Solution { public List<List<Integer>> reconstructMatrix(int upper, int lower, int[] colsum) { // early return int n = colsum.length; int totalSum = 0; for (int i = 0; i < n; i++) { totalSum += colsum[i]; } if (totalSum != upper + lower) return new ArrayList<List<Integer>>(); List<Integer> upperList = new ArrayList<>(n); List<Integer> lowerList = new ArrayList<>(n); for (int i = 0; i < n; i++) { if (lower < 0 || upper < 0) return new ArrayList<List<Integer>>(); if (colsum[i] == 0) { upperList.add(0); lowerList.add(0); } else if (colsum[i] == 1) { if (lower > upper) { upperList.add(0); lowerList.add(1); lower--; } else { upperList.add(1); lowerList.add(0); upper--; } } else { upperList.add(1); lowerList.add(1); upper--; lower--; } } List<List<Integer>> res = new ArrayList<>(2); res.add(upperList); res.add(lowerList); return res; } } ```
0
0
['Java']
0
reconstruct-a-2-row-binary-matrix
Beats 100 % | Brute to Optimal | Java Solution | Greedy | Array | ArrayLists | Collections |
beats-100-brute-to-optimal-java-solution-z0md
BruteForce Approach -> Beats 7%Complexity Time complexity: O(2n) Space complexity: O(1) CodeOptimal Approach -> Beats 100 %Complexity Time complexity: O(n) S
KarthikVarma19
NORMAL
2025-02-02T14:05:04.914016+00:00
2025-02-02T14:05:04.914016+00:00
9
false
# BruteForce Approach -> Beats 7% # Complexity - Time complexity: O(2n) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(1) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public List<List<Integer>> reconstructMatrix(int upper, int lower, int[] colsum) { List<List<Integer>> ans = new ArrayList<>(); ans.add(new ArrayList<Integer>()); ans.add(new ArrayList<Integer>()); int setBits = 0; //First Giving Priority to 2colsum for(int i = 0; i < colsum.length; i++) { ans.get(0).add(0); ans.get(1).add(0); if(colsum[i] == 2){ colsum[i] = 0; lower -= 1; upper -= 1; ans.get(0).set(i, 1); ans.get(1).set(i, 1); } setBits += colsum[i]; if((upper < 0) || (lower < 0)){ List<List<Integer>> empty = new ArrayList<>(); return empty; } } //Invalid Case if((upper + lower) != setBits) { List<List<Integer>> empty = new ArrayList<>(); return empty; } //Traversing and filling Upper Row and then Lower Row for(int col = 0; col < colsum.length; col++){ if(upper > 0 && colsum[col] > 0){ ans.get(0).set(col, 1); colsum[col] -= 1; upper -= 1; } if(lower > 0 && colsum[col] > 0){ ans.get(1).set(col, 1); colsum[col] -= 1; lower -= 1; } } return ans; } } ``` # Optimal Approach -> Beats 100 % <!-- Describe your first thoughts on how to solve this problem. --> # Complexity - Time complexity: O(n) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(1) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public List<List<Integer>> reconstructMatrix(int upper, int lower, int[] colsum) { int n = colsum.length; int mat[][] = new int[2][n]; for(int i = 0; i < n; i++) { if(colsum[i] == 0) continue; else if(colsum[i] == 2) { lower -= 1; upper -= 1; mat[0][i] = 1; mat[1][i] = 1; } else if(upper > lower) { mat[0][i] = 1; upper -= 1; } else{ mat[1][i] = 1; lower -= 1; } } if(upper != 0 || lower != 0){ return new ArrayList<>(); } return new ArrayList(Arrays.asList(mat[0], mat[1])); } } ```
0
0
['Array', 'Greedy', 'Java']
0
reconstruct-a-2-row-binary-matrix
1253. Reconstruct a 2-Row Binary Matrix
1253-reconstruct-a-2-row-binary-matrix-b-f16o
ApproachKeep adding 1 to the first row if upper >= lower, otherwise add it to the second row.Complexity Time complexity: O(n) Space complexity: O(2∗n) Code
wide0s
NORMAL
2025-01-28T13:52:35.919255+00:00
2025-01-28T13:52:35.919255+00:00
3
false
# Approach Keep adding 1 to the first row if upper >= lower, otherwise add it to the second row. # Complexity - Time complexity: $$O(n)$$ - Space complexity: $$O(2*n)$$ # Code ```python [] class Solution(object): def reconstructMatrix(self, upper, lower, colsum): """ :type upper: int :type lower: int :type colsum: List[int] :rtype: List[List[int]] """ n, m = 2, len(colsum) matrix = [ [0] * m for _ in range(n) ] for index in range(m): if colsum[index] == 1: # distribute 1 uniformly between arrays if upper >= lower and upper > 0: matrix[0][index] = 1 upper -= 1 elif lower > upper and lower > 0: matrix[1][index] = 1 lower -= 1 else: return [] elif colsum[index] == 2 and upper > 0 and lower > 0: matrix[1][index] = matrix[0][index] = 1 upper -= 1 lower -= 1 elif colsum[index] != 0: return [] return [] if upper > 0 or lower > 0 else matrix ```
0
0
['Python']
0
reconstruct-a-2-row-binary-matrix
26 ms Beats 100.00%
26-ms-beats-10000-by-krishna_s_chavan-ofgs
Complexity Time complexity: O(N) Code
krishna_s_chavan
NORMAL
2025-01-16T14:19:29.769817+00:00
2025-01-16T14:19:29.769817+00:00
4
false
# Complexity - Time complexity: O(N) # Code ```python [] class Solution(object): def reconstructMatrix(self, upper, lower, colsum): """ :type upper: int :type lower: int :type colsum: List[int] :rtype: List[List[int]] """ if upper+lower != sum(colsum): return [] xsum = 0 ysum = 0 ln = 2 ans = [[0] * len(colsum) for _ in range(2)] for x in range(len(colsum)): if colsum[x] == 2: ans[0][x] = 1 ans[1][x] = 1 xsum += 1 ysum +=1 for x,y in enumerate(colsum): if y == 1: if xsum != upper: ans[0][x] = 1 xsum +=1 else: ans[1][x] = 1 ysum += 1 if xsum== upper and ysum == lower: return ans return [] ```
0
0
['Python']
0
reconstruct-a-2-row-binary-matrix
Python O(n) greedy solution
python-on-greedy-solution-by-viniusck-k61q
Intuition Build the 2d matrix with two rows and try to fill out, the main cases are: If column ith is 2 then both cols need to be 1, if zero just skip it, if 1
viniusck
NORMAL
2025-01-14T15:58:09.116207+00:00
2025-01-14T15:58:09.116207+00:00
7
false
# Intuition - Build the 2d matrix with two rows and try to fill out, the main cases are: - If column ith is 2 then both cols need to be 1, if zero just skip it, if 1 then the 1 needs to be on either row (choose the one with expected larger sum greedy) - Check mid iteration if any of the contions have been violated, i.e., any of the rows is greater than expected. - Check in the final iteration if the sum has been reached # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O(n) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(n) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]: mat = [[0] * len(colsum) for _ in range(2)] if not upper and not lower: return mat rows_max = [upper, lower] rows_sum = [0, 0] for j in range(len(colsum)): csum = colsum[j] if csum == 2: mat[0][j] = 1 mat[1][j] = 1 rows_sum[0] += 1 rows_sum[1] += 1 elif csum == 1: if rows_max[0] >= rows_max[1]: mat[0][j] = 1 rows_sum[0] += 1 rows_max[0] -= 1 else: mat[1][j] = 1 rows_sum[1] += 1 rows_max[1] -= 1 if rows_sum[0] > upper: return [] if rows_sum[1] > lower: return [] if rows_sum[0] < upper or rows_sum[1] < lower: return [] return mat ```
0
0
['Python3']
0
reconstruct-a-2-row-binary-matrix
1253. Reconstruct a 2-Row Binary Matrix
1253-reconstruct-a-2-row-binary-matrix-b-iazo
IntuitionApproachComplexity Time complexity: Space complexity: Code
G8xd0QPqTy
NORMAL
2025-01-11T20:16:24.060328+00:00
2025-01-11T20:16:24.060328+00:00
3
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]: n = len(colsum) result = [[0] * n for _ in range(2)] for i in range(n): if colsum[i] == 2: if upper > 0 and lower > 0: result[0][i] = result[1][i] = 1 upper -= 1 lower -= 1 else: return [] elif colsum[i] == 1: if upper > lower: result[0][i] = 1 upper -= 1 elif lower >= upper: result[1][i] = 1 lower -= 1 else: return [] if upper == 0 and lower == 0: return result return [] ```
0
0
['Python3']
0
reconstruct-a-2-row-binary-matrix
Pyhton3 || Build a 2 row binary matrix
pyhton3-build-a-2-row-binary-matrix-by-d-nki0
IntuitionApproachwe are given 3 things upper - sum of upper row lower - sum of lower row cilsum- array of sum of ith column Conclusions we can draw from it - th
Divya_1422
NORMAL
2024-12-24T09:00:44.720388+00:00
2024-12-24T09:00:44.720388+00:00
3
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> we are given 3 things 1. upper - sum of upper row 2. lower - sum of lower row 3. cilsum- array of sum of ith column Conclusions we can draw from it - 1. there will always be 2 rows and n = len(colsum) will be the number of columns 2. if colsum[i] == 0 then both upper and lower row will be 0 3. if colsum[i] == 1 then either upper or lower row will be 1 4. if colsum[i] == 2 then both upper and lower will be 1 5. if sum(colsum) != lower + upper it is not valid Results - 1. we will have arrays seperate for both lower_row and upper_row 2. for every row we will check and put 1's and 0's accordingly by keep subtracting from lower and upper as we put more 1's 3. by the end both lower and upper should be 0 if not then it is a not valid case # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]: n = len(colsum) upper_row = [0]*n lower_row = [0]*n for i in range(n): if(colsum[i]==2): if(lower>0 and upper>0): upper_row[i] = 1 lower_row[i] = 1 upper -=1 lower -=1 else: return [] if(colsum[i]==1): if(upper>lower): upper_row[i] = 1 upper -=1 elif(lower>0): lower_row[i] = 1 lower -=1 else: return [] if(upper==0 and lower==0): return [upper_row, lower_row] else: return [] ```
0
0
['Python3']
0
reconstruct-a-2-row-binary-matrix
Swift solution
swift-solution-by-yan_feng-e4wz
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
yan_feng
NORMAL
2024-12-03T21:27:43.115920+00:00
2024-12-03T21:27:43.115945+00:00
0
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$$O(N)$$\n\n- Space complexity:\n$$O(N)$$\n\n# Code\n```swift []\nclass Solution {\n func reconstructMatrix(_ upper: Int, _ lower: Int, _ colsum: [Int]) -> [[Int]] {\n // Time: O(N)\n // Space: O(N)\n var res = Array(repeating: Array(repeating: 0, count: colsum.count), count: 2)\n var upper = upper, lower = lower\n for i in 0..<colsum.count {\n if colsum[i] == 2 {\n res[0][i] = 1\n res[1][i] = 1\n upper -= 1\n lower -= 1\n } else if colsum[i] == 1 {\n if upper > lower {\n res[0][i] = 1\n upper -= 1\n } else {\n res[1][i] = 1\n lower -= 1\n }\n }\n }\n return (0 == upper && 0 == lower) ? res : []\n }\n}\n```
0
0
['Swift']
0
reconstruct-a-2-row-binary-matrix
Java O(N)
java-on-by-wangcai20-cq4o
Intuition\n Describe your first thoughts on how to solve this problem. \nOne pass \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexi
wangcai20
NORMAL
2024-10-29T16:27:21.323065+00:00
2024-10-29T16:27:53.396741+00:00
5
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nOne pass \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public List<List<Integer>> reconstructMatrix(int upper, int lower, int[] colsum) {\n List<Integer> lUp = new ArrayList<>(), lLow = new ArrayList<>();\n for (int csum : colsum) {\n if (csum == 2) {\n lUp.add(1);\n lLow.add(1);\n upper--;\n lower--;\n } else if (csum == 0) {\n lUp.add(0);\n lLow.add(0);\n } else {\n if (upper >= lower) {\n lUp.add(1);\n lLow.add(0);\n upper--;\n } else {\n lUp.add(0);\n lLow.add(1);\n lower--;\n }\n }\n }\n if (upper != 0 || lower != 0)\n return new ArrayList(new ArrayList());\n return new ArrayList(List.of(lUp, lLow));\n }\n}\n```
0
0
['Java']
0
reconstruct-a-2-row-binary-matrix
Greedy Solution - Beats 98% :-D
greedy-solution-beats-98-d-by-astros-ikcm
Intuition\nJust a greedy solution which try to reconstruct the matry in a logical way, step by step.\n\n# Approach\n1. checks that the sum of upper and lower is
Astros
NORMAL
2024-10-24T21:24:52.064667+00:00
2024-10-24T21:24:52.064695+00:00
5
false
# Intuition\nJust a greedy solution which try to reconstruct the matry in a logical way, step by step.\n\n# Approach\n1. checks that the sum of `upper` and `lower` is equal to the sum of all the elements in `colsum`. This is a necessary condition to construct the solution. If this condition is not respected: we return `[]`.\n2. if `colssum[idx] == 2`, then there is a one in the `upper` row and one in the `lower` row. So we get rid of this cases.\n3. we distribuite the ones that are still in `colssum`.\n4. Finally, if we distribuited too much ones and `upper`, or `lower`, is negative, we should return `[]`.\n\n# Complexity\n- Time complexity: $$O(len(colsum))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(len(colsum))$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def reconstructMatrix(\n self, upper: int, lower: int, colsum: List[int]\n ) -> List[List[int]]:\n # step 1\n if upper + lower != sum(colsum):\n return []\n\n n = len(colsum)\n solution = [[0 for j in range(n)] for _ in range(2)]\n\n # step 2\n for idx in range(len(colsum)):\n if colsum[idx] == 2:\n solution[0][idx], solution[1][idx] = 1, 1\n colsum[idx] = 0\n upper -= 1\n lower -= 1\n\n # step 3\n for idx in range(len(colsum)):\n if colsum[idx] == 1:\n if upper > lower and solution[0][idx] == 0:\n upper -= 1\n solution[0][idx] += 1\n colsum[idx] -= 1\n elif lower >= upper and solution[1][idx] == 0:\n lower -= 1\n solution[1][idx] += 1\n colsum[idx] -= 1\n else:\n return []\n\n # step 4\n if upper < 0 or lower < 0:\n return []\n \n return solution\n\n```
0
0
['Python3']
0
reconstruct-a-2-row-binary-matrix
97% speed and 100% memory
97-speed-and-100-memory-by-belka-k7j2
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
belka
NORMAL
2024-10-20T03:07:17.096821+00:00
2024-10-20T03:07:17.096848+00:00
4
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]:\n c=Counter(colsum)\n if c[2]>upper or c[2]>lower:\n return []\n if max(upper,lower)+c[0]>len(colsum):\n return []\n res=[[-1]*len(colsum) for i in range(2)]\n for i,s in enumerate(colsum):\n if s==2:\n res[0][i],res[1][i]=1,1\n upper-=1\n lower-=1\n elif s==0:\n res[0][i],res[1][i]=0,0\n for i,s in enumerate(colsum):\n if s==1:\n if upper:\n res[0][i],res[1][i]=1,0\n upper-=1\n elif lower:\n res[0][i],res[1][i]=0,1\n lower-=1\n else:\n return []\n return res if upper==lower==0 else []\n \n\n\n```
0
0
['Python3']
0
reconstruct-a-2-row-binary-matrix
Python3 Greedy Solution Counting of 0,1,2 and fill columns as we go leverage invariants
python3-greedy-solution-counting-of-012-axeun
Intuition and Approach\nSee problem title\n\n# Complexity\nM, N := dims(grid)\n\n- Time complexity:\nO(MN)\n\n- Space complexity:\nO(MN) ( E ) O(1) ( I )\n\n# C
2018hsridhar
NORMAL
2024-10-16T03:30:22.939192+00:00
2024-10-16T03:30:22.939239+00:00
1
false
# Intuition and Approach\nSee problem title\n\n# Complexity\n$$M, N := dims(grid)$$\n\n- Time complexity:\n$$O(MN)$$\n\n- Space complexity:\n$$O(MN) ( E ) O(1) ( I )$$\n\n# Code\n```python3 []\n\'\'\'\nURL := https://leetcode.com/problems/reconstruct-a-2-row-binary-matrix/description/\n1253. Reconstruct a 2-Row Binary Matrix\n\'\'\'\nclass Solution:\n def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]:\n upperIdx = 0\n lowerIdx = 1\n upperPrime = upper\n lowerPrime = lower\n oneColCount = 0\n n = len(colsum)\n targetMatrix = [[0 for idx in range(n)] for j in range(2)]\n for ptr, colVal in enumerate(colsum):\n if(colVal == 2):\n targetMatrix[upperIdx][ptr] = 1\n targetMatrix[lowerIdx][ptr] = 1\n upperPrime -= 1\n lowerPrime -= 1\n elif(colVal == 1):\n oneColCount += 1\n if(upperPrime + lowerPrime != oneColCount or upperPrime < 0 or lowerPrime < 0):\n emptyMatrix = []\n return emptyMatrix\n for ptr,colVal in enumerate(colsum):\n if(colVal == 1):\n if(upperPrime > 0):\n targetMatrix[upperIdx][ptr] = 1\n upperPrime -= 1\n elif(upperPrime == 0 and lowerPrime > 0):\n targetMatrix[lowerIdx][ptr] = 1\n lowerPrime -= 1\n return targetMatrix\n\n \n```
0
0
['Array', 'Greedy', 'Matrix', 'Python3']
0
reconstruct-a-2-row-binary-matrix
High Low SupperPosition
high-low-supperposition-by-tonitannoury0-9w3y
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
tonitannoury01
NORMAL
2024-09-10T07:52:26.087712+00:00
2024-09-10T07:52:26.087738+00:00
0
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```javascript []\n/**\n * @param {number} upper\n * @param {number} lower\n * @param {number[]} colsum\n * @return {number[][]}\n */\nvar reconstructMatrix = function(upper, lower, colsum) {\n let res = Array(2).fill(0).map(()=>Array(colsum.length).fill(0))\n for(let sum = 0 ; sum < colsum.length ; sum++){\n if(colsum[sum] === 2){\n res[0][sum] = 1 \n res[1][sum] = 1 \n lower--\n upper--\n }else if(colsum[sum] === 0){\n continue\n }else if(colsum[sum] === 1){\n if(lower <= upper){\n res[0][sum] = 1\n upper--\n }else{\n res[1][sum] = 1\n lower--\n }\n }\n }\n if(lower !== 0 || upper !== 0){\n return []\n }\n return res\n};\n```
0
0
['JavaScript']
0
reconstruct-a-2-row-binary-matrix
Easy to understand
easy-to-understand-by-riteshhajare-meq6
Intuition and Approach\nGrid only consist of 0 or 1, and row size is 2. Now if column sum is 0 meaning both the rows of that column have value 0, if it is 2, bo
RiteshHajare
NORMAL
2024-09-06T19:03:09.850805+00:00
2024-09-06T19:03:09.850841+00:00
10
false
# Intuition and Approach\nGrid only consist of 0 or 1, and row size is 2. Now if column sum is 0 meaning both the rows of that column have value 0, if it is 2, both the columns of that row must have value 1, if it is 1, means either upper or lower row have value 1. If the upper is greater then we supposed to give that 1 to upper row of that column otherwise give to lower and recrease the sum of upper or lower or both according to condition.\n\nIf after performing this, upper and lower are not 0 ,(as it is the sum of rows) then answer cannot be found.Otherwise, return answer array.\n\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$ ($$O(n)$$ considering "ans" array) \n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<vector<int>> reconstructMatrix(int upper, int lower, vector<int>& colsum) {\n int n = colsum.size();\n \n vector<vector<int>>ans(2,vector<int>(n,0));\n\n for(int i=0;i<n;i++){\n int col = colsum[i];\n\n if(col == 2){\n upper--,lower--;\n ans[0][i] = ans[1][i] = 1;\n }else if(col == 1){\n if(upper>=lower){\n upper--;\n ans[0][i] = 1;\n }else{\n lower--;\n ans[1][i] = 1;\n }\n }\n }\n\n if(lower!=0 || upper != 0)\n return {};\n return ans;\n }\n};\n```
0
0
['C++']
0
reconstruct-a-2-row-binary-matrix
Easy to Understand - If-Else solution
easy-to-understand-if-else-solution-by-j-ndt5
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
jitesh3023
NORMAL
2024-08-25T02:46:03.732191+00:00
2024-08-25T02:46:03.732228+00:00
0
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<vector<int>> reconstructMatrix(int upper, int lower, vector<int>& colsum) {\n int u=0, l = 0;\n vector<vector<int>> ans(2, vector<int>(colsum.size(), 0));\n for(int i =0; i<colsum.size(); i++){\n if(colsum[i] == 0){\n ans[0][i] = 0;\n ans[1][i] = 0;\n }\n else if(colsum[i] == 2){\n ans[0][i] = 1;\n ans[1][i] = 1;\n u = u + ans[0][i];\n l = l + ans[1][i];\n }\n else if(colsum[i] == 1) {\n if(upper - u > lower - l) {\n ans[0][i] = 1;\n u += 1;\n } else {\n ans[1][i] = 1;\n l += 1;\n }\n }\n }\n if(u != upper || l != lower) {\n return {};\n }\n return ans;\n }\n};\n```
0
0
['C++']
0
reconstruct-a-2-row-binary-matrix
Super Simple || C++
super-simple-c-by-lotus18-z97d
Code\ncpp []\nclass Solution \n{\npublic:\n vector<vector<int>> reconstructMatrix(int upper, int lower, vector<int>& colsum) \n {\n int n=colsum.si
lotus18
NORMAL
2024-08-20T14:54:06.544352+00:00
2024-08-20T14:54:06.544412+00:00
1
false
# Code\n```cpp []\nclass Solution \n{\npublic:\n vector<vector<int>> reconstructMatrix(int upper, int lower, vector<int>& colsum) \n {\n int n=colsum.size();\n vector<vector<int>> grid(2, vector<int> (n,0));\n for(int x=0; x<n; x++)\n {\n if(colsum[x]==2) \n {\n if(upper>0 && lower>0)\n {\n grid[0][x]=grid[1][x]=1;\n upper--;\n lower--;\n }\n else\n {\n vector<vector<int>> t;\n return t; \n }\n }\n else if(colsum[x]==1)\n {\n if(upper>0 && upper>lower)\n {\n grid[0][x]=1;\n upper--;\n }\n else if(lower>0)\n {\n grid[1][x]=1;\n lower--;\n }\n else\n {\n vector<vector<int>> t;\n return t;\n }\n }\n }\n if(upper>0 || lower>0)\n {\n vector<vector<int>> t;\n return t;\n }\n return grid;\n }\n};\n```
0
0
['C++']
0
reconstruct-a-2-row-binary-matrix
Greedy C++
greedy-c-by-particle241-2elm
\n vector<vector<int>> reconstructMatrix(int upper, int lower, vector<int>& colsum) {\n int n = colsum.size();\n vector<vector<int>> ans(2, vec
particle241
NORMAL
2024-07-21T14:24:25.306164+00:00
2024-07-21T14:24:25.306205+00:00
0
false
```\n vector<vector<int>> reconstructMatrix(int upper, int lower, vector<int>& colsum) {\n int n = colsum.size();\n vector<vector<int>> ans(2, vector<int> (n, 0));\n \n int i = 0, j = 0;\n while(j < n){\n if(colsum[j] == 2){\n ans[0][j] = 1;\n ans[1][j] = 1;\n \n upper--;\n lower--;\n }\n else if(colsum[j] == 1){\n if(upper > lower){\n ans[0][j] = 1;\n upper--;\n }\n else{\n ans[1][j] = 1;\n lower--;\n }\n }\n j++;\n }\n \n return (upper == 0 && lower == 0) ? ans : vector<vector<int>> ();\n } \n```
0
0
['Greedy', 'C']
0
reconstruct-a-2-row-binary-matrix
C++ solution greedy
c-solution-greedy-by-oleksam-vvrk
\n// Please, upvote if you like it. Thanks :-)\nvector<vector<int>> reconstructMatrix(int upper, int lower, vector<int>& colsum) {\n\tint n = colsum.size();\n\t
oleksam
NORMAL
2024-07-21T07:48:23.276451+00:00
2024-07-21T07:48:23.276486+00:00
1
false
```\n// Please, upvote if you like it. Thanks :-)\nvector<vector<int>> reconstructMatrix(int upper, int lower, vector<int>& colsum) {\n\tint n = colsum.size();\n\tint sum = accumulate(begin(colsum), end(colsum), 0);\n\tif (upper + lower != sum)\n\t\treturn {};\n\tvector<vector<int>> res(2, vector<int>(n));\n\tfor (int i = 0; i < n; i++) {\n\t\tif (colsum[i] == 2) {\n\t\t\tres[0][i] = res[1][i] = 1;\n\t\t\tupper--, lower--;\n\t\t}\n\t\telse if (colsum[i] == 1) {\n\t\t\tif (upper > lower)\n\t\t\t\tres[0][i] = 1, upper--;\n\t\t\telse\n\t\t\t\tres[1][i] = 1, lower--;\n\t\t}\n\t}\n\tif (lower == 0 && upper == 0)\n\t\treturn res;\n\treturn {};\n}\n```
0
0
['Array', 'Greedy', 'C', 'Matrix', 'C++']
0
reconstruct-a-2-row-binary-matrix
Easy cpp
easy-cpp-by-deshmukhrao-5fl1
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
DeshmukhRao
NORMAL
2024-07-21T05:48:55.194147+00:00
2024-07-21T05:48:55.194180+00:00
1
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> reconstructMatrix(int upper, int lower, vector<int>& colsum) {\n \n vector<vector<int>>ans(2,vector<int>(colsum.size(),0));\n\n for(int i=0;i<colsum.size();i++)\n {\n if(colsum[i]==1)\n {\n if(upper>lower)\n {\n ans[0][i]=1;\n upper--;\n }\n else\n {\n ans[1][i] =1;\n lower--;\n }\n }\n\n if(colsum[i]==2)\n {\n ans[0][i]=1;\n ans[1][i] =1;\n\n lower--;\n upper--;\n }\n\n\n // chceck invalid cases\n\n if(upper<0 && lower<0)\n {\n return {};\n }\n }\n\n if(upper!=0 or lower!=0) \n return {};\n \n return ans;\n\n\n }\n};\n```
0
0
['C++']
0
reconstruct-a-2-row-binary-matrix
Greedy Javascript || Easy to understand
greedy-javascript-easy-to-understand-by-cj0ta
\n\n# Code\n\nfunction reconstructMatrix(upper: number, lower: number, colsum: number[]): number[][] {\n let grid = Array(2).fill(0).map(() => Array(colsum.l
omrocks
NORMAL
2024-07-20T16:58:25.812708+00:00
2024-07-20T16:58:25.812725+00:00
6
false
\n\n# Code\n```\nfunction reconstructMatrix(upper: number, lower: number, colsum: number[]): number[][] {\n let grid = Array(2).fill(0).map(() => Array(colsum.length).fill(0));\n let j = 0, k = 0;\n\n if(colsum.reduce((a, b) => a + b, 0) != upper + lower) {\n return []\n }\n\n const twos = colsum.filter((item) => item == 2).length;\n\n if(lower < twos) return [];\n if(upper < twos) return []\n\n for(let i = 0; i < colsum.length; i++) {\n if(colsum[i] == 2 && upper != 0 && lower != 0) {\n upper -= 1;\n lower -= 1;\n grid[0][j] = 1;\n grid[1][k] = 1;\n }\n j++;\n k++;\n }\n\n j = 0;\n k = 0;\n \n for(let i = 0; i < colsum.length; i++) {\n if(colsum[i] == 1) {\n if(upper != 0) {\n grid[0][j] = 1;\n upper -= 1\n } else if(lower != 0) {\n grid[1][k] = 1;\n lower -= 1;\n }\n }\n j++;\n k++;\n }\n\n \n console.log(\'last\', lower, upper)\n return grid;\n return [[],[]]\n};\n```
0
0
['Greedy', 'TypeScript', 'JavaScript']
0
reconstruct-a-2-row-binary-matrix
✅💯🔥Explanations No One Will Give You🎓🧠Very Detailed Approach🎯🔥Extremely Simple And Effective🔥
explanations-no-one-will-give-youvery-de-2tur
Complexity\n- Time complexity:\n Add your time complexity here, e.g. O(n) \n O(N*2)\n\n- Space complexity:\n Add your space complexity here, e.g. O(n) \n
vish2925
NORMAL
2024-07-20T16:45:34.186314+00:00
2024-07-20T16:45:34.186345+00:00
4
false
# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(N*2)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(1)\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> reconstructMatrix(int u, int l, vector<int>& c) {\n vector<vector<int>>ans(2,vector<int>(c.size(),0));\n int n=c.size();\n\n int sum=0;\n for(int i:c) sum+=i;\n if((u+l) != sum) return {};\n\n for(int i=0;i<n;i++){\n if(c[i]==0) continue;\n\n else if(c[i]==2){\n ans[0][i]=1;\n ans[1][i]=1;\n u--;\n l--;\n }\n }\n if(u<0 or l<0) return {};\n for(int i=0;i<n;i++){\n if(c[i]==1){\n if(u){\n u--;\n ans[0][i]=1;\n }\n else{\n l--;\n ans[1][i]=1;\n }\n }\n }\n\n\n return ans;\n }\n};\n```
0
0
['Array', 'Greedy', 'Matrix', 'C++']
0
reconstruct-a-2-row-binary-matrix
Simple Java Greedy Approach Beats 95.67%....Hope it helps
simple-java-greedy-approach-beats-9567ho-ymia
O(n)# 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-
thevedant
NORMAL
2024-07-20T14:24:55.388789+00:00
2024-07-20T14:24:55.388821+00:00
10
false
$$O(n)$$# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n\nclass Solution {\n public List<List<Integer>> reconstructMatrix(int upper, int lower, int[] colSum) {\n int [] rowSum = {upper ,lower};\n int row = 2;\n int col = colSum.length;\n Integer[][] ans =new Integer[2][col];\n List<List<Integer>> aaa = new ArrayList<>();\n \n for(int j = 0 ; j<col ; j++){\n \n if(colSum[j] == 2){\n ans[0][j] = 1;\n ans[1][j] = 1;\n rowSum[0]-=1;\n rowSum[1]-=1;\n } if (colSum[j] == 0){\n ans[0][j] = 0;\n ans[1][j] = 0;\n }if(colSum[j] ==1){\n if(rowSum[0] < rowSum[1]){\n ans[0][j] = 0;\n ans[1][j] = 1;\n rowSum[1]-=1;\n }else{\n ans[0][j] = 1;\n ans[1][j] = 0;\n rowSum[0] -=1;\n }\n }\n\n if(rowSum[0] < 0 || rowSum[1] <0)return aaa;\n }\n\n if(rowSum[0] != 0 || rowSum[1] != 0)return aaa;\n \n \n aaa.add(Arrays.asList(ans[0]));\n aaa.add(Arrays.asList(ans[1]));\n\n return aaa;\n }\n \n}\n```\n
0
0
['Greedy', 'Java']
0
reconstruct-a-2-row-binary-matrix
C++|| O(N) Solution Step By Step
c-on-solution-step-by-step-by-nal1ns1ngh-kzy3
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem involves reconstructing a binary matrix based on the given upper and lower
Nal1nS1ngh
NORMAL
2024-07-20T12:21:23.845711+00:00
2024-07-20T12:21:23.845733+00:00
14
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem involves reconstructing a binary matrix based on the given upper and lower sums and a colsum array. The idea is to allocate the \'1\'s in each column such that the sum of the rows matches the given upper and lower values while adhering to the constraints provided by colsum.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1> Initialization: Create a 2D vector v with 2 rows and columns equal to the size of colsum, initialized to 0.\n\n2> Distribute \'2\'s: If an element in colsum is 2, both rows must have a \'1\' in that column. Decrement upper and lower accordingly.\n\n3> Distribute \'1\'s: If an element in colsum is 1, place a \'1\' in the row which has remaining sum to distribute. Prefer placing \'1\' in the upper row first if it has remaining capacity.\n\n4>Validation: After placing all \'1\'s, check if upper and lower have reached 0. If not, return an empty matrix indicating it\'s not possible to form such a matrix.\n\n5>Return Result: If valid, return the constructed matrix.\n# Complexity\n- Time complexity: O(n), where \uD835\uDC5B is the size of colsum. We iterate through the colsum array twice.\n# - Space complexity: O(n), the space used to store the resulting 2D vector.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> reconstructMatrix(int upper, int lower, vector<int>& colsum) {\n vector<vector<int>>v(2, vector<int>(colsum.size(),0));\n for(int k = 0; k<colsum.size(); k++){\n if(colsum[k]==2 && upper>0 && lower>0){\n v[0][k]=1;\n v[1][k]=1;\n upper--;\n lower--;\n colsum[k]=0;\n }\n }\n for(int k = 0; k<colsum.size();k++){\n if(colsum[k]==1&&upper>0){\n v[0][k]=1;\n upper--;\n colsum[k]=0;\n }else if(colsum[k]==1&&lower>0){\n v[1][k]=1;\n lower--;\n colsum[k]=0;\n }\n }\n bool b = true;\n for(int i = 0; i<colsum.size(); i++){\n if(colsum[i]>0){\n b = false;\n break;\n }\n }\n if(upper>0 || lower>0){\n b=false;\n }\n if(b){\n return v;\n }else{\n v.clear();\n return v;\n }\n }\n};\n```
0
0
['C++']
0
reconstruct-a-2-row-binary-matrix
Easy to understand. Simple Greedy approach. Beats 80% of the solutions in TC.
easy-to-understand-simple-greedy-approac-32nh
Intuition\nGreedy as filling of matrix mostly gets solved with it.\n\n# Approach\n1) As there are two rows only and digit could be 0 and 1 only so max column su
anmolbansal029
NORMAL
2024-07-20T11:29:17.449641+00:00
2024-07-20T11:29:17.449675+00:00
2
false
# Intuition\nGreedy as filling of matrix mostly gets solved with it.\n\n# Approach\n1) As there are two rows only and digit could be 0 and 1 only so max column sum can be 2 so assign 1 each to both blocks of that column\nand subtract upper and lower by 1.\n2) And if column sum is 1 then by greedy select if upper or lower is not yet 0 then assign accordingly and subtract;\n3) During the loop if any of the conditions not satisfy then return {}.\n4) Final check if upper or lower is not zero then also return {}.\n5) Otherwise return the ans 2D ans matrix;\n\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> reconstructMatrix(int upper, int lower, vector<int>& colsum) {\n int m = colsum.size();\n vector<vector<int>> ans(2, vector<int>(m, 0));\n \n for (int j = 0; j < m; ++j) {\n if (colsum[j] == 2) {\n // If colsum[j] is 2, both rows must have a 1 in this column\n if (upper > 0 && lower > 0) {\n ans[0][j] = 1;\n ans[1][j] = 1;\n upper--;\n lower--;\n } else {\n return {}; \n }\n }\n }\n \n for (int j = 0; j < m; ++j) {\n if (colsum[j] == 1) {\n // If colsum[j] is 1, we need to decide which row to place the 1 in\n if (upper > 0) {\n ans[0][j] = 1;\n upper--;\n } else if (lower > 0) {\n ans[1][j] = 1;\n lower--;\n } else {\n return {}; // Not enough upper or lower sum to satisfy colsum[j]\n }\n }\n }\n \n // After filling, both upper and lower sums should be zero\n if (upper != 0 || lower != 0) {\n return {};\n }\n\n return ans;\n }\n};\n\n```
0
0
['Array', 'Greedy', 'Matrix', 'C++']
0
reconstruct-a-2-row-binary-matrix
The Shortest Possible Javascript Solution
the-shortest-possible-javascript-solutio-rxgs
\n\nvar reconstructMatrix = function(upper, lower, colsum, total = upper + lower) {\n const upperArr = colsum.map(v => v === 2 ? (upper--, 1) : 0).map((v, i)
charnavoki
NORMAL
2024-07-20T09:09:32.302298+00:00
2024-07-20T09:09:56.721945+00:00
2
false
\n```\nvar reconstructMatrix = function(upper, lower, colsum, total = upper + lower) {\n const upperArr = colsum.map(v => v === 2 ? (upper--, 1) : 0).map((v, i) => colsum[i] === 1 && upper ? (upper--, 1) : v);\n if (total !== colsum.reduce((x, y) => x + y) || upper) {\n return [];\n }\n return [upperArr, colsum.map((v, i) => v - upperArr[i])];\n};\n```\n\n#### it\'s a challenge for you to explain how it works\n#### please upvote, you motivate me to solve problems in original ways
0
0
['JavaScript']
0
reconstruct-a-2-row-binary-matrix
7 ms Beats 93.10%
7-ms-beats-9310-by-songshengtao1-qfvf
Intuition\n Describe your first thoughts on how to solve this problem. \nGreedy algorithm.\n\n# Approach\n Describe your approach to solving the problem. \n\nIt
songshengtao1
NORMAL
2024-07-20T02:16:54.309277+00:00
2024-07-20T02:16:54.309301+00:00
13
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nGreedy algorithm.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nIterate the `colsum` array.\n\n* Case 1: sum = 0. No number to fill in. Skip.\n* Case 2: sum = 1. Choose to fill in the row that has larger row sum.\n* Case 3: sum = 2. Have to fill in two rows.\n\nOperation fill in is done by set value to `1` and decrease the row sum. If row sum is lower than zero, return empty array.\n\n# Complexity\n- Time complexity: $$O(N)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(N)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public List<List<Integer>> reconstructMatrix(int upper, int lower, int[] colsum) {\n List<List<Integer>> result = new ArrayList<>();\n final int N = colsum.length;\n Integer[] row1 = new Integer[N];\n Arrays.fill(row1, 0);\n Integer[] row2 = new Integer[N];\n Arrays.fill(row2, 0);\n\n for (int i = 0; i < N; ++i) {\n if (colsum[i] == 2) {\n --upper;\n if (upper < 0) {\n return result;\n }\n row1[i] = 1;\n --lower;\n if (lower < 0) {\n return result;\n }\n row2[i] = 1;\n } else if (colsum[i] == 1) {\n if (upper > lower) {\n --upper;\n if (upper < 0) {\n return result;\n }\n row1[i] = 1;\n } else {\n --lower;\n if (lower < 0) {\n return result;\n }\n row2[i] = 1;\n }\n }\n }\n\n if (upper != 0 || lower != 0) {\n return result;\n }\n\n result.add(Arrays.asList(row1));\n result.add(Arrays.asList(row2));\n return result;\n }\n}\n```
0
0
['Java']
0
reconstruct-a-2-row-binary-matrix
C# Iterative solution O(n)
c-iterative-solution-on-by-sgasilov-d2f1
Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n\npublic class Solution {\n public IList<IList<int>> ReconstructMatrix(int upper
sgasilov
NORMAL
2024-07-20T02:03:30.091636+00:00
2024-07-20T02:03:30.091655+00:00
3
false
# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\npublic class Solution {\n public IList<IList<int>> ReconstructMatrix(int upper, int lower, int[] colsum)\n {\n var result = new List<IList<int>>()\n {\n Enumerable.Repeat(0, colsum.Length).ToList(),\n Enumerable.Repeat(0, colsum.Length).ToList()\n };\n\n for (int col = 0; col < colsum.Length; col++)\n {\n if (colsum[col] == 0)\n {\n continue;\n }\n\n if (colsum[col] == 2)\n {\n upper--;\n lower--;\n result[0][col] = 1;\n result[1][col] = 1;\n continue;\n }\n\n if (lower == 0 || upper > lower)\n {\n upper--;\n result[0][col] = 1;\n }\n else\n {\n lower--;\n result[1][col] = 1;\n }\n }\n\n if (upper != 0 || lower != 0)\n {\n return new List<IList<int>>();\n }\n\n return result;\n }\n}\n```
0
0
['C#']
0
reconstruct-a-2-row-binary-matrix
JS solution - simulation
js-solution-simulation-by-makhey-rnh9
Code\n\n/**\n * @param {number} upper\n * @param {number} lower\n * @param {number[]} colsum\n * @return {number[][]}\n */\nvar reconstructMatrix = function(upp
MakHey
NORMAL
2024-07-20T01:59:05.647136+00:00
2024-07-20T01:59:05.647167+00:00
1
false
# Code\n```\n/**\n * @param {number} upper\n * @param {number} lower\n * @param {number[]} colsum\n * @return {number[][]}\n */\nvar reconstructMatrix = function(upper, lower, colsum) {\n const matrix = Array.from({length: 2}, ()=> Array(colsum.length).fill(0))\n\n // PHASE 1: if colsum[i] === 2, obviously it use 1 digit from upper and lower\n for(let i = 0; i < colsum.length; i++){\n if(colsum[i] === 2){\n matrix[0][i] = 1\n matrix[1][i] = 1\n upper--\n lower--\n }\n }\n\n // PHASE 2: when colsum[i] === 1, use digit from max(upper, lower) -> think greedy\n for(let i = 0; i < colsum.length; i++){\n if(colsum[i] === 1){\n if(upper > lower){\n matrix[0][i] = 1\n upper--\n } else {\n matrix[1][i] = 1\n lower--\n }\n }\n }\n\n\n // PHASE 3: check if upper and lower are all used \n if(upper !== 0 || lower !== 0) return []\n\n return matrix\n};\n```
0
0
['JavaScript']
0
reconstruct-a-2-row-binary-matrix
Kotlin evenly allocation
kotlin-evenly-allocation-by-dmoney29-hx0g
Code\n\nclass Solution {\n \n var upperList = mutableListOf<Int>()\n var lowerList = mutableListOf<Int>()\n var result: List<List<Int>>
dmoney29
NORMAL
2024-06-23T01:07:03.701924+00:00
2024-06-23T01:07:03.701951+00:00
0
false
# Code\n```\nclass Solution {\n \n var upperList = mutableListOf<Int>()\n var lowerList = mutableListOf<Int>()\n var result: List<List<Int>> = listOf(upperList, lowerList)\n var upperCnt = 0\n var lowerCnt = 0\n fun reconstructMatrix(upper: Int, lower: Int, colsum: IntArray): List<List<Int>> {\n upperCnt = upper\n lowerCnt = lower\n colsum.forEach {\n when(it) {\n 2 -> {\n when {\n upperCnt > 0 && lowerCnt > 0 -> addOneBoth()\n else -> return emptyList()\n }\n }\n 1 -> when {\n upperCnt > 0 && upperCnt >= lowerCnt -> {\n addOneUpper()\n }\n lowerCnt > 0 && lowerCnt >= upperCnt -> {\n addOneLower()\n }\n else -> return emptyList()\n }\n 0 -> addZeorBoth()\n }\n }\n if(upperCnt != 0 || lowerCnt != 0) {\n return emptyList()\n }\n return result\n }\n\n fun addOneBoth(){\n upperList.add(1)\n upperCnt--\n lowerList.add(1)\n lowerCnt--\n // println("uppercnt= $upperCnt | lowerCnt = $lowerCnt")\n // println("addOneBoth: " + upperList.toString() + " | " + lowerList.toString())\n }\n\n fun addZeorBoth(){\n upperList.add(0)\n lowerList.add(0)\n // println("uppercnt= $upperCnt | lowerCnt = $lowerCnt")\n // println("addZeorBoth: " + upperList.toString()+ " | " + lowerList.toString())\n }\n\n fun addOneUpper(){\n upperList.add(1)\n upperCnt--\n lowerList.add(0)\n // println("uppercnt= $upperCnt | lowerCnt = $lowerCnt")\n // println("addOneUpper: " + upperList.toString() + " | " + lowerList.toString())\n }\n\n fun addOneLower(){\n upperList.add(0)\n lowerList.add(1)\n lowerCnt--\n // println("uppercnt= $upperCnt | lowerCnt = $lowerCnt")\n // println("addOneLower: " + upperList.toString() + " | " + lowerList.toString())\n }\n}\n```
0
0
['Kotlin']
0
reconstruct-a-2-row-binary-matrix
Java Code
java-code-by-kpuniya-c9jh
import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class Solution {\n public List> reconstructMatrix(int upper, int lowe
Kpuniya
NORMAL
2024-06-22T03:01:59.733289+00:00
2024-06-22T03:01:59.733313+00:00
0
false
import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class Solution {\n public List<List<Integer>> reconstructMatrix(int upper, int lower, int[] colsum) {\n int n = colsum.length;\n int count1 = 0;\n int count2 = 0;\n\n for (int i = 0; i < n; i++) {\n if (colsum[i] == 1) count1++;\n if (colsum[i] == 2) count2 += 2;\n }\n\n if ((upper + lower) - (count1 + count2) != 0) return new ArrayList<>();\n\n int upp = upper - count2 / 2;\n int low = lower - count2 / 2;\n\n if (upp < 0 || low < 0) return new ArrayList<>();\n\n List<List<Integer>> res = new ArrayList<>();\n res.add(new ArrayList<>());\n res.add(new ArrayList<>());\n\n for (int i = 0; i < n; i++) {\n if (colsum[i] == 2) {\n res.get(0).add(1);\n res.get(1).add(1);\n } else if (colsum[i] == 1) {\n if (upp > 0) {\n res.get(0).add(1);\n res.get(1).add(0);\n upp--;\n } else {\n res.get(0).add(0);\n res.get(1).add(1);\n low--;\n }\n } else {\n res.get(0).add(0);\n res.get(1).add(0);\n }\n }\n\n return res;\n }\n}\n
0
0
[]
0
reconstruct-a-2-row-binary-matrix
C solution | O(n)
c-solution-on-by-anshadk-r7vo
Approach\n Describe your approach to solving the problem. \nIf current colsum[i] is 0 or 2 assign both rows accordingly (both 0 or 1).\n\nIf colsum[i] is 1 assi
anshadk
NORMAL
2024-06-21T13:36:30.343749+00:00
2024-06-21T13:36:30.343780+00:00
1
false
# Approach\n<!-- Describe your approach to solving the problem. -->\nIf current `colsum[i]` is `0` or `2` assign both rows accordingly (both `0` or `1`).\n\nIf `colsum[i]` is `1` assign `1` to the row which have higher left over row sum.\n\nDecrement row sums after each value accordingly to the assigned value.\n\nIf final values of `upper` or `lower` are not zero, then it is impossible.\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n) for result\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nint** reconstructMatrix(int upper, int lower, int* colsum, int colsumSize, int* returnSize, int** returnColumnSizes) {\n int **res = malloc(2 * sizeof(int *));\n *returnSize = 2;\n\n *returnColumnSizes = malloc(2 * sizeof(int));\n (*returnColumnSizes)[0] = (*returnColumnSizes)[1] = colsumSize;\n\n res[0] = malloc(colsumSize * sizeof(int));\n res[1] = malloc(colsumSize * sizeof(int));\n\n for(int i = 0; i < colsumSize; i++) {\n if(colsum[i] == 1) {\n res[0][i] = (upper >= lower);\n res[1][i] = 1 - res[0][i];\n } else {\n res[0][i] = res[1][i] = (bool)colsum[i];\n }\n upper -= res[0][i];\n lower -= res[1][i];\n }\n if(upper || lower) {\n *returnSize = 0;\n return NULL;\n }\n return res;\n}\n```
0
0
['C']
0
reconstruct-a-2-row-binary-matrix
20ms || Greedy || Explanation || Beginner friendly
20ms-greedy-explanation-beginner-friendl-r5dp
Intuition\nThe most important thing to notice in the problem is that if the sum of the current column is zero, both cells have to be zero and if the sum is two
Momcho
NORMAL
2024-06-15T22:43:13.812358+00:00
2024-06-15T22:43:13.812383+00:00
17
false
# Intuition\nThe most important thing to notice in the problem is that if the sum of the current column is zero, both cells have to be zero and if the sum is two - both cells will be equal to one.\n\n# Approach\nThe greedy approach consists of two iterations of the \'colsum\' array. On the first go we fill the cells which value we know (0 or 2), and on the second iteration we fill the columns with values of one depending on how much ones we can place on the upper and the lower row. In the end we check for leftover cells we need to fill and if we have - we return an empty array.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> reconstructMatrix(int upper, int lower, vector<int>& colsum) {\n ios_base :: sync_with_stdio(0), cin.tie(0), cout.tie(0);\n\n //The matrix containing the answer\n vector < vector <int> > ans(2, vector <int> (colsum.size(), 0));\n\n //First iteration\n for (int i = 0; i < colsum.size(); i++)\n {\n //If the colsum is zero we ignore it\n if (!colsum[i])\n continue;\n \n //If it is two we fill both cells and we \n //decrease the values of upper and lower\n if (colsum[i] == 2)\n {\n upper--;\n lower--;\n ans[0][i] = 1;\n ans[1][i] = 1;\n }\n\n //If we filled more cells than required\n //return an empty array\n if (upper < 0 || lower < 0)\n return {};\n }\n\n //Second iteration\n for (int i = 0; i < colsum.size(); i++)\n if (colsum[i] == 1)\n {\n //If we can fill the upper cell we fill it\n if (upper > 0)\n {\n upper--;\n ans[0][i] = 1;\n }\n //If we can\'t we fill the bottom one\n else\n {\n lower--;\n ans[1][i] = 1;\n }\n\n //If we run out of cells to fill \n //we return an empty arrat\n if (lower < 0)\n return {};\n }\n\n //If the lower and upper values are both zero\n //then and only then we return the matrix\n if (!lower && !upper)\n return ans;\n\n return {};\n }\n};\n```
0
0
['C++']
0
reconstruct-a-2-row-binary-matrix
Solution with explanation
solution-with-explanation-by-alekseiapa-aohm
Approach\n Describe your approach to solving the problem. \n\n- Check the basic conditions: The sum of all elements in the colsum array must be equal to upper +
alekseiapa
NORMAL
2024-05-24T02:30:16.015842+00:00
2024-05-24T02:30:16.015859+00:00
1
false
# Approach\n<!-- Describe your approach to solving the problem. -->\n\n- Check the basic conditions: The sum of all elements in the colsum array must be equal to upper + lower. If this condition is not met, there is no valid solution.\n- Initialize a 2-D matrix with dimensions 2xn.\n- Iterate through each column, and decide the values of the matrix based on the value of colsum[i]:\n- If colsum[i] == 2, both elements in the upper and lower row of this column must be 1.\n- If colsum[i] == 1, one element should be 1 and the other should be 0. Prioritize setting the upper row to 1 until upper reaches 0, then set the lower row.\n- If colsum[i] == 0, both elements should be 0.\nAfter processing all columns, verify if the sums of the upper and lower rows are as expected. If not, return an empty array.\n\n\n# Code\n```\nfunc reconstructMatrix(upper int, lower int, colsum []int) [][]int {\n\tn := len(colsum)\n\tresult := make([][]int, 2)\n\tresult[0] = make([]int, n)\n\tresult[1] = make([]int, n)\n\n\tsumOfCols := 0\n\tfor _, val := range colsum {\n\t\tsumOfCols += val\n\t}\n\n\tif sumOfCols != upper+lower {\n\t\treturn [][]int{}\n\t}\n\n\tfor i, col := range colsum {\n\t\tswitch col {\n\t\tcase 2:\n\t\t\tif upper > 0 && lower > 0 {\n\t\t\t\tresult[0][i] = 1\n\t\t\t\tresult[1][i] = 1\n\t\t\t\tupper--\n\t\t\t\tlower--\n\t\t\t} else {\n\t\t\t\treturn [][]int{}\n\t\t\t}\n\t\tcase 1:\n\t\t\tif upper > lower {\n\t\t\t\tresult[0][i] = 1\n\t\t\t\tupper--\n\t\t\t} else if lower > 0 {\n\t\t\t\tresult[1][i] = 1\n\t\t\t\tlower--\n\t\t\t} else {\n\t\t\t\treturn [][]int{}\n\t\t\t}\n\t\tcase 0:\n\t\t\tresult[0][i] = 0\n\t\t\tresult[1][i] = 0\n\t\tdefault:\n\t\t\treturn [][]int{}\n\t\t}\n\t}\n\n\tif upper != 0 || lower != 0 {\n\t\treturn [][]int{}\n\t}\n\n\treturn result\n}\n```
0
0
['Go']
0
reconstruct-a-2-row-binary-matrix
Python 3 solution beats 92%
python-3-solution-beats-92-by-iloabachie-p2lj
\n\n# Code\npy\nclass Solution:\n def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]:\n rowsum = [upper, lower]
iloabachie
NORMAL
2024-05-10T14:23:38.106410+00:00
2024-05-11T12:44:34.355232+00:00
32
false
![image.png](https://assets.leetcode.com/users/images/b3d9efe1-4b90-4ab5-a474-cf4c3cb3a2c2_1715431448.0712533.png)\n\n# Code\n```py\nclass Solution:\n def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]:\n rowsum = [upper, lower] \n if (twos := colsum.count(2)) > min(rowsum) or sum(rowsum) != sum(colsum):\n return [] \n grid = [[0 for c in colsum] for r in rowsum] \n row, col = len(rowsum), len(colsum) \n for i in range(row):\n rowsum[i] -= twos\n for j in range(col): \n if colsum[j] == 2:\n grid[i][j] = 1\n elif colsum[j] == 0 or rowsum[i] == 0:\n continue\n else:\n grid[i][j] = 1\n rowsum[i] -= 1\n colsum[j] -= 1\n return grid \n```
0
0
['Python3']
0
reconstruct-a-2-row-binary-matrix
1253. Reconstruct a 2-Row Binary Matrix.cpp
1253-reconstruct-a-2-row-binary-matrixcp-78qa
Code\n\nclass Solution {\npublic:\n vector<vector<int>> reconstructMatrix(int upper, int lower, vector<int>& col) {\n int n = col.size();\n vec
202021ganesh
NORMAL
2024-05-07T10:00:30.105616+00:00
2024-05-07T10:00:30.105638+00:00
1
false
**Code**\n```\nclass Solution {\npublic:\n vector<vector<int>> reconstructMatrix(int upper, int lower, vector<int>& col) {\n int n = col.size();\n vector<vector<int>>res(2,vector<int>(n,0));\n vector<int>colsum(col.begin(),col.end()); \n int rowsum [2] = {upper,lower};\n for(int j=0;j<n;j++)\n {\n if(colsum[j]==2)\n {\n res[0][j] = 1;\n res[1][j] = 1;\n colsum[j] = 0;\n rowsum[0] -= 1;\n rowsum[1] -= 1;\n }\n }\n for(int i=0;i<2;i++)\n {\n for(int j=0;j<n;j++)\n {\n if(res[i][j]!=1)\n {\n res[i][j] = (rowsum[i]>0 && colsum[j]>0) ? 1 : 0;\n rowsum[i] -= res[i][j];\n colsum[j] -= res[i][j];\n }\n } \n }\n int t_upper = 0;\n int t_lower = 0;\n for(int i=0;i<n;i++)\n {\n t_upper+=res[0][i];\n t_lower+=res[1][i]; \n if(col[i]!=(res[0][i]+res[1][i]))return {};\n } \n if(t_upper != upper || t_lower!=lower)return {}; \n return res;\n }\n};\n```
0
0
['C']
0
find-the-difference-of-two-arrays
Easy Solution C++ 🔥 Explained 🔥 Using Sets
easy-solution-c-explained-using-sets-by-y3j52
PLEASE UPVOTE \uD83D\uDC4D\n# Intuition\n- ##### To solve this problem, we can create two sets: set1 and set2. We can then iterate through nums1 and add each in
ribhav_32
NORMAL
2023-05-03T05:21:49.235663+00:00
2023-05-03T08:54:05.804218+00:00
31,700
false
# **PLEASE UPVOTE \uD83D\uDC4D**\n# Intuition\n- ##### To solve this problem, we can create two sets: set1 and set2. We can then iterate through nums1 and add each integer to set1. Similarly, we can iterate through nums2 and add each integer to set2.\n\n- ##### Next, we can take the set difference between set1 and set2 to obtain the distinct integers in nums1 that are not present in nums2. Similarly, we can take the set difference between set2 and set1 to obtain the distinct integers in nums2 that are not present in nums1.\n\n- ##### Finally, we can return the results in the form of a Vector of size 2, where the first element is the vector of distinct integers in nums1 that are not present in nums2, and the second element is the vector of distinct integers in nums2 that are not present in nums1.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Complexity\n- ### Time complexity: O(M+N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- ### Space complexity: O(M+N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# **PLEASE UPVOTE \uD83D\uDC4D**\n# Code\n```\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 \n vector<int> distinct_nums1, distinct_nums2;\n for (int num : set1) {\n if (set2.count(num) == 0) {\n distinct_nums1.push_back(num);\n }\n }\n\n for (int num : set2) {\n if (set1.count(num) == 0) {\n distinct_nums2.push_back(num);\n }\n }\n\n return {distinct_nums1, distinct_nums2};\n }\n};\n\n```\n![e2515d84-99cf-4499-80fb-fe458e1bbae2_1678932606.8004954.png](https://assets.leetcode.com/users/images/e5cc6438-63d7-47fb-84d1-e4e36cf43c6e_1683003574.1370602.png)\n
297
2
['Array', 'Ordered Set', 'C++']
5
find-the-difference-of-two-arrays
set_difference
set_difference-by-votrubac-x34s
C++\ncpp\nvector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n vector<int> v1, v2;\n set<int> s1(begin(nums1), end(nums1)), s2(b
votrubac
NORMAL
2022-03-27T04:02:03.794584+00:00
2022-03-27T04:02:03.794621+00:00
12,836
false
**C++**\n```cpp\nvector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n vector<int> v1, v2;\n set<int> s1(begin(nums1), end(nums1)), s2(begin(nums2), end(nums2));\n set_difference(begin(s1), end(s1), begin(s2), end(s2), back_inserter(v1));\n set_difference(begin(s2), end(s2), begin(s1), end(s1), back_inserter(v2));\n return {v1, v2};\n}\n```
105
2
['C']
16
find-the-difference-of-two-arrays
[Python] Set difference
python-set-difference-by-lee215-zlgw
Explanation\n\nCalculate the set difference.\n\nTime O(n)\nSpace O(n)\n\n\n\nPython\npy\n def findDifference(self, nums1, nums2):\n s1, s2 = set(nums1
lee215
NORMAL
2022-03-27T04:22:03.544863+00:00
2022-03-27T04:22:03.544912+00:00
9,671
false
# **Explanation**\n\nCalculate the set difference.\n\nTime `O(n)`\nSpace `O(n)`\n<br>\n\n\n**Python**\n```py\n def findDifference(self, nums1, nums2):\n s1, s2 = set(nums1), set(nums2)\n return [list(s1 - s2), list(s2 - s1)]\n```\n
96
0
[]
12
find-the-difference-of-two-arrays
✅ Simple solution using Set, O(n), Explained and commented
simple-solution-using-set-on-explained-a-grys
If you\'ll like the explanation, do UpVote :)\n## Algorithm:\n\t\t1. First create 2 sets. Then add nums1 elements to set1, and nums2 to set2.This will give us 2
karankhara
NORMAL
2022-03-27T04:03:03.097001+00:00
2022-04-12T01:18:43.429728+00:00
12,781
false
If you\'ll like the explanation, do **UpVote** :)\n## Algorithm:\n\t\t1. First create 2 sets. Then add nums1 elements to set1, and nums2 to set2.This will give us 2 sets with unique elements only.\n\t\t2. Now, just iterate to all elements of set1 and add those elements to first sublist of result list, which are not in set2.\n\t\t3. Similarly, iterate to all elements of set2 and add those elements to second sublist of result list, which are not in set1.\n\t\t4. Now, we got our result list.\n\n## Complexity:\n\t\tTime: O(n) : n is length of input array with bigger length\n\t\tSpace: O(m) : m is size of hashset with bigger length\n\n## Code:\n\tclass Solution {\n\t\tpublic List<List<Integer>> findDifference(int[] nums1, int[] nums2) {\n\t\t\tSet<Integer> set1 = new HashSet<>(); // create 2 hashsets\n\t\t\tSet<Integer> set2 = new HashSet<>();\n\t\t\tfor(int num : nums1){ set1.add(num); } // add nums1 elements to set1\n\t\t\tfor(int num : nums2){ set2.add(num); } // add nums2 elements to set2\n\t\t\t\n\t\t\tList<List<Integer>> resultList = new ArrayList<>(); // Initialize result list with 2 empty sublists that we will return\n\t\t\tresultList.add(new ArrayList<>());\n\t\t\tresultList.add(new ArrayList<>());\n\n\t\t\tfor(int num : set1){ // just iterate to all elements of set1\n\t\t\t\tif(!set2.contains(num)){ resultList.get(0).add(num); } // add those elements to first sublist of result list, which are not in set2.\n\t\t\t}\n\t\t\tfor(int num : set2){ // just iterate to all elements of set2\n\t\t\t\tif(!set1.contains(num)){ resultList.get(1).add(num); } // add those elements to first sublist of result list, which are not in set1\n\t\t\t}\n\t\t\treturn resultList;\n\t\t}\n\t}\n\t\nIf you need more explanation or, if got even more optimized way, let me know.\t\nIf you like the explanation, pls **UpVote** :)
82
0
['Java']
8
find-the-difference-of-two-arrays
Easy Solution Of JAVA 🔥C++🔥Using Set 🔥Beginner Friendly 🔥
easy-solution-of-java-cusing-set-beginne-uhav
\n\n# Code\nPLEASE UPVOTE IF YOU LIKE.\n\nclass Solution {\n public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {\n List<List<Integer
shivrastogi
NORMAL
2023-05-03T00:51:29.440908+00:00
2023-05-03T00:58:03.103443+00:00
19,637
false
\n\n# Code\nPLEASE UPVOTE IF YOU LIKE.\n```\nclass Solution {\n public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {\n List<List<Integer>> ans = new ArrayList<List<Integer>>();\n List<Integer> ans1 = new ArrayList<Integer>();\n List<Integer> ans2 = new ArrayList<Integer>();\n Set<Integer> set1 = new HashSet<Integer>();\n Set<Integer> set2 = new HashSet<Integer>(); \n \n for(int n : nums1) set1.add(n);\n for(int n : nums2) set2.add(n);\n for (int n : set1){\n if(set2.contains(n) == false){\n ans1.add(n);\n }\n }\n for (int n : set2){\n if(set1.contains(n) == false){\n ans2.add(n);\n }\n }\n ans.add(ans1);\n ans.add(ans2);\n return ans;\n }\n}\n```\nC++\n```\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n\t\tvector<vector<int>> ans = {{},{}};\n\t\t\n\t\t// Create set with elements of the vector\n unordered_set<int> s1(nums1.begin(),nums1.end());\n unordered_set<int> s2(nums2.begin(),nums2.end());\n \n\t\t// For every element in set A that is not present in set B\n\t\t// Add it to the answer, do this for both set\n for(auto x : s1) if(!s2.count(x)) ans[0].push_back(x);\n for(auto x : s2) if(!s1.count(x)) ans[1].push_back(x);\n\t\t\n return ans;\n }\n};\n```
73
2
['C++', 'Java']
7
find-the-difference-of-two-arrays
💯Efficient Set Approach for Finding Difference in Two Arrays
efficient-set-approach-for-finding-diffe-r2fa
Intuition\n- Imagine nums1 and nums2 as two sets of marbles. You want to find the marbles that are on only one table, not on both.\n- The unordered sets act li
Abhishek_bharti1
NORMAL
2024-07-09T07:57:55.333873+00:00
2024-07-09T07:57:55.333895+00:00
8,620
false
# Intuition\n- Imagine nums1 and nums2 as two sets of marbles. You want to find the marbles that are on only one table, not on both.\n- The unordered sets act like hash tables, allowing for quick checks to see if a specific marble exists in the other set. \n- We iterate through each marble in one set, checking if it\'s present in the other set. If not, it\'s unique and gets added to the result.\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1) ***Populate Unordered Sets:*** \n - We insert the elements from nums1 and nums2 into s1 and s2 respectively, using their iterators.\n2) ***Find Elements Unique to nums1:***\n - We iterate through each element (num) in nums1.\n - For each num:\n - We use find(num) in s2 to check if num exists in the other set (nums2).\n - If find(num) == s2.end() (meaning num is not found in s2), it\'s unique to nums1. We add it to the first sub-vector in ans.\n3) ***Find Elements Unique to nums2:***\n - We repeat the process for nums2. We iterate through each element (num) and check if it exists in s1. If it doesn\'t, it\'s unique to nums2 and is added to the second sub-vector in ans.\n\n# Complexity\n- Time complexity: ***O(n + m)***\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: ***O(n + m)***\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 set<int> s1,s2;\n vector<vector<int>> ans(2);\n for(auto i : nums1){\n s1.insert(i);\n }\n for(auto i : nums2){\n s2.insert(i);\n }\n for(auto i : s1){\n if(s2.find(i) == s2.end()){\n ans[0].push_back(i);\n }\n }\n for(auto i : s2){\n if(s1.find(i) == s1.end()){\n ans[1].push_back(i);\n }\n }\n return ans;\n }\n};\n```\n```python []\nclass Solution:\n def findDifference(self, nums1, nums2):\n s1, s2 = set(nums1), set(nums2)\n ans = [[], []]\n\n for i in s1:\n if i not in s2:\n ans[0].append(i)\n \n for i in s2:\n if i not in s1:\n ans[1].append(i)\n \n return ans\n\n```\n```java []\nimport java.util.*;\n\nclass Solution {\n public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {\n Set<Integer> s1 = new HashSet<>();\n Set<Integer> s2 = new HashSet<>();\n List<List<Integer>> ans = new ArrayList<>();\n ans.add(new ArrayList<>());\n ans.add(new ArrayList<>());\n\n for (int i : nums1) {\n s1.add(i);\n }\n \n for (int i : nums2) {\n s2.add(i);\n }\n\n for (int i : s1) {\n if (!s2.contains(i)) {\n ans.get(0).add(i);\n }\n }\n\n for (int i : s2) {\n if (!s1.contains(i)) {\n ans.get(1).add(i);\n }\n }\n\n return ans;\n }\n}\n\n```\n```javascript []\nvar findDifference = function(nums1, nums2) {\n let s1 = new Set(nums1);\n let s2 = new Set(nums2);\n let ans = [[], []];\n\n for (let i of s1) {\n if (!s2.has(i)) {\n ans[0].push(i);\n }\n }\n\n for (let i of s2) {\n if (!s1.has(i)) {\n ans[1].push(i);\n }\n }\n\n return ans;\n};\n\n```\nPLEASE UPVOTE !!! \uD83D\uDE4F\n\n![Gemini_Generated_Image_3dhm323dhm323dhm.jpg](https://assets.leetcode.com/users/images/81cfcf90-7ae0-4b9a-807b-8d59aac17ebd_1720511129.4538867.jpeg)\n
42
0
['Hash Table', 'Ordered Set', 'C++', 'Java', 'Python3', 'JavaScript']
3
find-the-difference-of-two-arrays
[Javascript] Whatever another array has, just DELETE them!
javascript-whatever-another-array-has-ju-sqpb
Let\'s create a set ofnums1, then DELETE all values innums2.\n\n> Note: No need to check ifnums1has it, just delete them all away!\n\n\nlet ans1=new Set(nums1)\
lynn19950915
NORMAL
2022-03-31T16:58:44.111056+00:00
2023-05-27T06:09:01.790246+00:00
3,797
false
Let\'s create a set of`nums1`, then **DELETE all values in**`nums2`.\n\n> Note: No need to check if`nums1`has it, just delete them all away!\n\n```\nlet ans1=new Set(nums1)\nnums2.forEach(v=>{ans1.delete(v)});\nlet ans2=new Set(nums2);\nnums1.forEach(v=>{ans2.delete(v)}); \n\nreturn [[...ans1],[...ans2]];\n```\n\nThanks for your reading and **up-voting** :)\n\n**\u2B50 Check [HERE](https://github.com/Lynn19950915/LeetCode_King) for my full Leetcode Notes ~**\n
40
0
['Ordered Set', 'JavaScript']
6
find-the-difference-of-two-arrays
C++ Hash Set
c-hash-set-by-lzl124631x-uj71
See my latest update in repo LeetCode\n\n## Solution 1. Hash Set \n\ncpp\n// OJ: https://leetcode.com/contest/weekly-contest-286/problems/find-the-difference-of
lzl124631x
NORMAL
2022-03-27T04:02:17.761070+00:00
2022-03-27T04:02:17.761114+00:00
4,824
false
See my latest update in repo [LeetCode](https://github.com/lzl124631x/LeetCode)\n\n## Solution 1. Hash Set \n\n```cpp\n// OJ: https://leetcode.com/contest/weekly-contest-286/problems/find-the-difference-of-two-arrays/\n// Author: github.com/lzl124631x\n// Time: O(A + B)\n// Space: O(A + B)\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& A, vector<int>& B) {\n unordered_set<int> sa(begin(A), end(A)), sb(begin(B), end(B));\n vector<vector<int>> ans(2);\n for (int n : sa) {\n if (sb.count(n) == 0) ans[0].push_back(n);\n }\n for (int n : sb) {\n if (sa.count(n) == 0) ans[1].push_back(n);\n }\n return ans;\n }\n};\n```
36
1
[]
5
find-the-difference-of-two-arrays
Java Streams solution
java-streams-solution-by-climberig-k1jw
```java\n public List> findDifference(int[] a1, int[] a2){\n Set s1 = Arrays.stream(a1).boxed().collect(Collectors.toSet());\n Set s2 = Arrays.str
climberig
NORMAL
2022-03-27T04:09:27.842927+00:00
2022-03-27T04:28:07.482060+00:00
3,584
false
```java\n public List<List<Integer>> findDifference(int[] a1, int[] a2){\n Set<Integer> s1 = Arrays.stream(a1).boxed().collect(Collectors.toSet());\n Set<Integer> s2 = Arrays.stream(a2).filter(n -> !s1.contains(n)).boxed().collect(Collectors.toSet());\n Arrays.stream(a2).forEach(s1::remove);\n return Arrays.asList(new ArrayList<>(s1), new ArrayList<>(s2));\n }
35
1
['Java']
2
find-the-difference-of-two-arrays
[ Python ] [ Set Implementation ] [ Easy Approach ]
python-set-implementation-easy-approach-68kxd
Code\n\nclass Solution:\n def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:\n res=[]\n a=[]\n a=set(nums1
Sosuke23
NORMAL
2023-05-03T04:15:15.929767+00:00
2023-05-03T04:15:15.929796+00:00
8,784
false
# Code\n```\nclass Solution:\n def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:\n res=[]\n a=[]\n a=set(nums1) - set(nums2)\n b=[]\n b=set(nums2) - set(nums1)\n res.append(a)\n res.append(b)\n return res\n```
31
1
['Python3']
3
find-the-difference-of-two-arrays
C++ || Easy || 2 methods || brute -> optimize
c-easy-2-methods-brute-optimize-by-amank-de2a
Intuition\n\nSearch a (element of Array1 ) in Array 2 , if it is not present in Array-> it is part of our answer of Array1 part.\n\nRepeate same for Array2\n\nA
amankatiyar783597
NORMAL
2023-05-03T03:13:02.671727+00:00
2023-05-03T03:13:02.671753+00:00
8,357
false
# Intuition\n***\nSearch a (element of Array1 ) in Array 2 , if it is not present in Array-> it is part of our answer of Array1 part.\n\nRepeate same for Array2\n\nAdd both part in another 2D Array \n\n# Approach 1\n***\nLet\'s Store all Element in set so that no repeating element is not there and also we can use the count method (To find the presense of a element in set).\n\nItrate Over one set and find presence in second set --->\n-> if element present in second set = skip\n-> if not -> store to our answer vector\n` HERE , CONUT FUCTION RETURN 0 IF ELEMENT IS NOT PRESENT OTHERWISE 1 `\n***\n```\nHOPE YOU LIKE IT !! PLEASE VOTE UP...\n```\n***\n\n# Complexity\n- Time complexity:\nO(N*log(N))\n- Space complexity:\nO(N)\n\n# Code 1 (N*log(N))\n***\n```\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n\t\tvector<vector<int>> ans = {{},{}};\n set<int> s1(nums1.begin(),nums1.end());\n set<int> s2(nums2.begin(),nums2.end());\n \n\n for(auto x : s1){\n if(s2.count(x)==0) ans[0].push_back(x);\n }\n for(auto x : s2){\n if(s1.count(x)==0) ans[1].push_back(x);\n }\n\t\t\n return ans;\n }\n};\n```\n***\n```\nHOPE YOU LIKE IT !! PLEASE VOTE UP...\n```\n***\n# Approach 2\n***\nThis is simple bruet force \n\nItrate Over one Array and find presence in second Array --->\n-> if element present in second Array = skip\n-> if not -> store to our answer vector\n\n# Complexity\n- Time complexity:\nO(N*N)\n- Space complexity:\nO(N)\n# Code 2 (N*N)\n***\n```\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n set<int> st;\n vector<vector<int>> ans;\n for(int a : nums1){\n int f=1;\n for(int b : nums2){\n if(a==b) f=0;\n }\n if(f) st.insert(a);\n }\n vector<int> tp;\n for(int a : st){\n tp.push_back(a);\n }\n ans.push_back(tp);\n st.clear();\n tp.clear();\n for(int a : nums2){\n int f=1;\n for(int b : nums1){\n if(a==b) f=0;\n }\n if(f) st.insert(a);\n }\n for(int a : st){\n tp.push_back(a);\n }\n ans.push_back(tp);\n return ans;\n }\n};\n```\n\n***\n```\nHOPE YOU LIKE IT !! PLEASE VOTE UP...\n```\n***\n
30
1
['C++']
1
find-the-difference-of-two-arrays
Simple JS Solution with Set
simple-js-solution-with-set-by-34days-xerp
\n# Complexity\nRunTime 95%\nO(n) or idk :)\n\n# Code\n\nvar findDifference = function(nums1, nums2) {\n \n nums1 = new Set(nums1)\n nums2 = new Set(nu
34days
NORMAL
2023-05-03T06:37:39.575596+00:00
2023-05-03T06:37:39.575639+00:00
2,922
false
\n# Complexity\nRunTime 95%\nO(n) or idk :)\n\n# Code\n```\nvar findDifference = function(nums1, nums2) {\n \n nums1 = new Set(nums1)\n nums2 = new Set(nums2)\n\n for (let item of nums1){\n if (nums2.has(item)) {\n nums1.delete(item)\n nums2.delete(item)\n }\n }\n return [Array.from(nums1),Array.from(nums2)]\n \n};\n```
24
0
['JavaScript']
4
find-the-difference-of-two-arrays
C++ || 4 different approaches || sort, unique, set_difference, set, unordered_set, copy_if, bitset
c-4-different-approaches-sort-unique-set-jn3q
TODO(heder): Insert cute cat meme to ask for up-votes. ;)\n\nPlease let me know if you came up with another approach or if you have some suggestions how to impo
heder
NORMAL
2022-03-27T20:22:19.297373+00:00
2023-05-05T17:02:43.384896+00:00
1,943
false
**TODO(heder): Insert cute cat meme to ask for up-votes. ;)**\n\nPlease let me know if you came up with another approach or if you have some suggestions how to imporve one of the following approaches.\n\n# Approach 1: std::sort, std::unique, and std::set_difference\n\nIn order to use ```std::set_difference``` the inputs need to be sorted, and since we are only looking for distinct numbers we need to call ```std::unique``` too. This approach modifies the input.\n\n```cpp\n static vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n sort(begin(nums1), end(nums1));\n nums1.erase(unique(begin(nums1), end(nums1)), end(nums1));\n sort(begin(nums2), end(nums2));\n nums2.erase(unique(begin(nums2), end(nums2)), end(nums2));\n vector<vector<int>> ans(2);\n ans[0].reserve(size(nums1));\n ans[1].reserve(size(nums2));\n set_difference(begin(nums1), end(nums1), begin(nums2), end(nums2), back_inserter(ans[0]));\n set_difference(begin(nums2), end(nums2), begin(nums1), end(nums1), back_inserter(ans[1]));\n return ans;\n }\n```\n\n**Complexity Analysis**\n\n* Time complexity: $$O(n \\log n)$$, because the run time is dominated by ```std::sort```, ```std::unique``` and ```std::set_difference``` are both linear.\n\n* Space complexity: $$O(1)$$ no extra memory needed. I am not taking the result into account. Maybe we should.\n\n## Variant 1: std::sort, std::unique, and rewrite in-place\n\nThis variant is inspired by @Satj, after we have sorted and "unique-yfied" the input we can rewrite them together.\n\n```cpp\n static vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n // sort and unique\n sort(begin(nums1), end(nums1));\n nums1.erase(unique(begin(nums1), end(nums1)), end(nums1));\n sort(begin(nums2), end(nums2));\n nums2.erase(unique(begin(nums2), end(nums2)), end(nums2));\n int i1 = 0;\n int i2 = 0;\n int o1 = 0;\n int o2 = 0;\n // "merge"\n while (i1 < size(nums1) && i2 < size(nums2)) {\n if (nums1[i1] == nums2[i2]) {\n ++i1;\n ++i2;\n } else if (nums1[i1] < nums2[i2]) {\n nums1[o1++] = nums1[i1++];\n } else {\n nums2[o2++] = nums2[i2++];\n }\n }\n // handle the rest\n while (i1 < size(nums1)) nums1[o1++] = nums1[i1++];\n nums1.resize(o1);\n while (i2 < size(nums2)) nums2[o2++] = nums2[i2++];\n nums2.resize(o2); \n return {nums1, nums2}; \n }\n```\n\n**Complexity Analysis**\n\n* Time complexity: $$O(n \\log n)$$, because the run time is dominated by ```std::sort```, ```std::unique``` and "merge" and handling the rest are all linear.\n\n* Space complexity: $$O(1)$$ no extra memory needed, we don\'t even have extra output vectors.\n\n# Variant 2: std::sort and "merge" we de-duping\n\nWe can take this a step further and handle the unique elements while merging. The code gets quite long though.\n\n```cpp\n static vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n // sort\n sort(begin(nums1), end(nums1));\n sort(begin(nums2), end(nums2));\n int i1 = 0;\n int i2 = 0;\n int o1 = 0;\n int o2 = 0;\n // "merge"\n while (i1 < size(nums1) && i2 < size(nums2)) {\n if (i1 > 0) {\n while (i1 < size(nums1) && nums1[i1 - 1] == nums1[i1]) ++i1;\n if (i1 == size(nums1)) break;\n }\n if (i2 > 0) {\n while (i2 < size(nums2) && nums2[i2 - 1] == nums2[i2]) ++i2;\n if (i2 == size(nums2)) break;\n }\n if (nums1[i1] == nums2[i2]) {\n ++i1;\n ++i2;\n } else if (nums1[i1] < nums2[i2]) {\n nums1[o1++] = nums1[i1++];\n } else {\n nums2[o2++] = nums2[i2++];\n }\n }\n // handle the rest\n while (i1 < size(nums1)) {\n if (i1 > 0) {\n while (i1 < size(nums1) && nums1[i1 - 1] == nums1[i1]) ++i1;\n if (i1 == size(nums1)) break;\n }\n nums1[o1++] = nums1[i1++];\n }\n nums1.resize(o1);\n while (i2 < size(nums2)) {\n if (i2 > 0) {\n while (i2 < size(nums2) && nums2[i2 - 1] == nums2[i2]) ++i2;\n if (i2 == size(nums2)) break;\n }\n nums2[o2++] = nums2[i2++];\n }\n nums2.resize(o2); \n return {nums1, nums2}; \n }\n```\n\n**Complexity Analysis**\nIs basically the same as variant 1.\n\n# Approach 2: std::set and std::set_difference\n\nIf we turn the input vectors into ```std::set```s we can do the `sort | unique` in one go. We are also not modifying the input.\n\n```cpp\n static vector<vector<int>> findDifference(const vector<int>& nums1, const vector<int>& nums2) {\n const set<int> s1(begin(nums1), end(nums1));\n const set<int> s2(begin(nums2), end(nums2));\n vector<vector<int>> ans(2);\n ans[0].reserve(size(nums1));\n ans[1].reserve(size(nums2));\n set_difference(begin(s1), end(s1), begin(s2), end(s2), back_inserter(ans[0]));\n set_difference(begin(s2), end(s2), begin(s1), end(s1), back_inserter(ans[1]));\n return ans;\n }\n```\n\n**Complexity Analysis**\n\n* Time complexity: $$O(n \\log n)$$ which comes from creating the sets.\n\n* Space complexity: $$O(n)$$ we need the extra memory for the sets\n\n# Approach 3: std::unordered_set and std::copy_if\n\nIt doesn\'t matter in which order we return the numbers in the answer, so we can use an ```std::unordered_set``` as well.\n\n```cpp\n static vector<vector<int>> findDifference(const vector<int>& nums1, const vector<int>& nums2) {\n const unordered_set<int> s1(begin(nums1), end(nums1));\n const unordered_set<int> s2(begin(nums2), end(nums2));\n vector<vector<int>> ans(2);\n ans[0].reserve(size(nums1));\n ans[1].reserve(size(nums2));\n copy_if(begin(s1), end(s1), back_inserter(ans[0]), [&](int x) { return !s2.count(x); });\n copy_if(begin(s2), end(s2), back_inserter(ans[1]), [&](int x) { return !s1.count(x); });\n return ans;\n }\n```\n\n**Complexity Analysis**\n\n* Time complexity: $$O(size(nums1) + size(nums2))$$\n\n* Space complexity: $$O(size(nums1) + size(nums2)$$\n\n# Approach 4: std::bitset\n\nSince we know that the numbers in ```nums1``` and ```nums2``` are limited to the range ```-1000``` to ```1000``` we can just use a ```bitset<>``` if we apply and offset to make the index non negative. The drawback is that we need to check the entire ```bitset<>```, we could keep tracking of the smallest and the biggest number in the input vectors.\n\n```cpp\n static vector<vector<int>> findDifference(const vector<int>& nums1, const vector<int>& nums2) {\n bitset<2048> s1;\n for (int num : nums1) s1.set(num + 1024);\n bitset<2048> s2;\n for (int num : nums2) s2.set(num + 1024);\n \n vector<vector<int>> ans(2);\n ans[0].reserve(size(nums1));\n ans[1].reserve(size(nums2));\n for (int i = 0; i < size(s1); ++i) {\n if (s1[i] && !s2[i]) {\n ans[0].push_back(i - 1024);\n } else if (!s1[i] && s2[i]) {\n ans[1].push_back(i - 1024);\n }\n }\n return ans;\n }\n```\n\nThe following version keeps track of smallest and biggest number in the input vectors, and seems to a bit faster for the current test sets, but the code is also more complicated:\n\n```cpp\n static vector<vector<int>> findDifference(const vector<int>& nums1, const vector<int>& nums2) {\n bitset<2048> s1;\n int mx = -1024;\n int mn = 1024;\n for (int num : nums1) {\n mn = min(mn, num);\n mx = max(mx, num);\n s1.set(num + 1024);\n }\n bitset<2048> s2;\n for (int num : nums2) {\n mn = min(mn, num);\n mx = max(mx, num);\n s2.set(num + 1024);\n }\n \n vector<vector<int>> ans(2);\n ans[0].reserve(size(nums1));\n ans[1].reserve(size(nums2));\n for (int i = mn + 1024; i <= mx + 1024; ++i) {\n if (s1[i] && !s2[i]) {\n ans[0].push_back(i - 1024);\n } else if (!s1[i] && s2[i]) {\n ans[1].push_back(i - 1024);\n }\n }\n return ans;\n }\n```\n\n... and yes, I agree we should likely factor out ```1024``` into a constant.\n\n**Complexity Analysis**\n\n* Time complexity: $$O(size(nums1) + size(nums2))$$ we still need to process all the input. For very small inputs the cost will be dominated by scanning the bitset\n\n* Space complexity: $$O(1)$$, even if a big 1, if we consider the value range fixed. :) As @Satj pointed out it would be more accurate to describe it as $$O(M)$$ where $$M$$ is the possible value range of the input, which is for this problem fixed to -1000 to 1000.\n\n_As always: Feedback, questions, and comments are welcome, and leave a like (aka upvote) before you leave. :)_\n
22
0
['C', 'Sorting', 'Ordered Set']
1
find-the-difference-of-two-arrays
Solved using Set property||Efficient||Faster||Easy||Time Complexity: O(n)||Space Complexity: O(n)
solved-using-set-propertyefficientfaster-l36u
Intuition\n Describe your first thoughts on how to solve this problem. \nBrute Force: For each element in the first array, check if it exists in the second arra
Mohammed_Raziullah_Ansari
NORMAL
2023-05-05T22:17:35.743171+00:00
2023-05-05T22:17:35.743203+00:00
1,084
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBrute Force: For each element in the first array, check if it exists in the second array. If it does not, add it to the result array. This method has a time complexity of O(n^2) and is not recommended for large arrays.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach used in this solution is to first convert both input lists into sets, which have O(1) lookup time. Then, we use the set difference operator - to find the values that are in set1 but not in set2, and the values that are in set2 but not in set1. Finally, we convert the resulting sets back into lists and return them as a list of two lists.\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:\n # Convert both lists to sets\n set1 = set(nums1)\n set2 = set(nums2)\n # Get the elements that are in set1 but not in set2\n ans1 = list(set1 - set2)\n # Get the elements that are in set2 but not in set1\n ans2 = list(set2 - set1)\n # Return the results as a list of two lists\n return [ans1, ans2]\n\n\n```
19
0
['Array', 'Math', 'Ordered Set', 'Python3']
6
find-the-difference-of-two-arrays
+97%, very simple solution
97-very-simple-solution-by-yxasika-dz9k
Intuition\nBy the unique-constraint it is helpful to think about using Sets.\n\n# Approach\nCreating two Sets by the given input, we can filter the first entrie
yxasika
NORMAL
2023-03-08T21:33:27.202391+00:00
2023-03-08T21:33:27.202419+00:00
927
false
# Intuition\nBy the unique-constraint it is helpful to think about using Sets.\n\n# Approach\nCreating two Sets by the given input, we can filter the first entries by its non-occurence in the second Set. By using the `delete`-function of the Set we get the information, whether the number is inside of the Set as well as deleting the item in the second Set. Since we cleaned the second Set in the first `filter`-Step we can parse this directly as the second answer Array.\n\n# Complexity\n- Time complexity:\nLooking at the actual filtering (Set-parsind not put into account), we only have to iterate through the first array once. Therefore the Time-complexity arguable could be $$O(n)$$.\n\n\n# Code\n```\nfunction findDifference(nums1: number[], nums2: number[]): number[][] {\n // Creating two Sets for both Array of numbers.\n const [ansSet1, ansSet2] = [new Set(nums1), new Set(nums2)];\n \n return [\n // Filtering the first Set by occurences in the second Set via delete\n // we get a filtered Set for the second answer-item.\n [...ansSet1].filter(n => !ansSet2.delete(n)),\n [...ansSet2]\n ];\n};\n```
18
0
['TypeScript']
4
find-the-difference-of-two-arrays
Java Two Sets Solution - O(N)
java-two-sets-solution-on-by-ethank_6-r5pr
\nclass Solution {\n public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {\n List<List<Integer>> result = new ArrayList<>();\n
ethank_6
NORMAL
2022-03-27T06:52:54.952810+00:00
2022-03-27T06:52:54.952853+00:00
2,828
false
```\nclass Solution {\n public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {\n List<List<Integer>> result = new ArrayList<>();\n \n\t\t// Initialize each array as a set\n Set<Integer> list1 = new HashSet<>();\n for (int n : nums1) {\n list1.add(n);\n }\n \n Set<Integer> list2 = new HashSet<>();\n for (int n : nums2) {\n list2.add(n);\n }\n \n List<Integer> unique1 = new ArrayList<>();\n List<Integer> unique2 = new ArrayList<>();\n \n\t\t// For each distinct number in array 1, we check if that number is contained in array 2.\n\t\t// If it is, we know that number is not unique to either set, therefore we can remove it from set 2.\n\t\t// If the number isn\'t found in set 2, we know it is unique to set 1, and we can add it to our result.\n for (int n : list1) {\n if (list2.contains(n)) {\n list2.remove(n);\n } else {\n unique1.add(n);\n }\n }\n \n\t\t// All remaining numbers in set 2 weren\'t in set 1, so they are uniqe to array 2.\n for (int n : list2) {\n unique2.add(n);\n }\n \n result.add(unique1);\n result.add(unique2);\n \n return result;\n }\n}\n```\n\nUsing hashsets are perfect for this problem, as we can not only check if a set contains a number in constant lookup time but also remove duplicates inherently. \n\nSteps:\n1) Build two sets out of our passed in arrays.\n2) Iterate through the first set. If the second set contains a number in the first set, we remove it from the second set (cause it is a dupe). Otherwise, we add it to our resulting list.\n3) All remaining numbers in the second set are unique to array 2, so we can add them to our result.\n\nHope this helps, let me know if I missed anything.
18
0
['Java']
3
find-the-difference-of-two-arrays
[Python] simple 1 line
python-simple-1-line-by-f1re-9r6g
\ndef findDifference(self, a: List[int], b: List[int]) -> List[List[int]]:\n return [set(a)-set(b), set(b)-set(a)]\n
f1re
NORMAL
2022-03-27T04:07:29.126872+00:00
2022-03-27T04:07:29.126925+00:00
1,833
false
```\ndef findDifference(self, a: List[int], b: List[int]) -> List[List[int]]:\n return [set(a)-set(b), set(b)-set(a)]\n```
18
0
['Python']
1
find-the-difference-of-two-arrays
🔍 [VIDEO] Find the 🔢 Difference of Two Arrays
video-find-the-difference-of-two-arrays-56c6p
Intuition\n\nOur first thoughts on solving this problem revolve around the concept of set differences. Given two integer arrays, we need to find the unique inte
vanAmsen
NORMAL
2023-07-29T11:58:24.040508+00:00
2023-07-29T11:58:24.040529+00:00
1,711
false
# Intuition\n\nOur first thoughts on solving this problem revolve around the concept of set differences. Given two integer arrays, we need to find the unique integers in the first array that are not in the second, and vice versa. The idea of set difference fits perfectly here. \n\nhttps://youtu.be/eo-NwnOjF1Q\n\n# Approach\n\nWe approach this problem by leveraging the capabilities of Python sets. Here are the steps:\n\n1. Convert the input lists to sets. This serves two purposes: it removes any duplicate elements, and it allows us to perform set operations. \n\n2. Use the `-` operator to find the difference between the sets. This gives us the elements that are in one set but not in the other.\n\n3. Convert the resulting sets back to lists and return them.\n\n# Complexity\n\n- Time complexity: The time complexity of our solution is \\(O(n)\\), where \\(n\\) is the length of the longer input list. This is because we iterate through each list once to convert it to a set.\n\n- Space complexity: The space complexity of our solution is also \\(O(n)\\), where \\(n\\) is the length of the longer input list. This is because we create a new set for each input list.\n\nThis Python code defines a function `findDifference` that finds and returns the difference between two input arrays. The function is part of a class `Solution`, as required by the LeetCode problem format.\n\n# Code\n\n```Python []\nfrom typing import List\n\nclass Solution:\n def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:\n set1 = set(nums1)\n set2 = set(nums2)\n diff1 = set1 - set2\n diff2 = set2 - set1\n return [list(diff1), list(diff2)]\n```\n``` C++ []\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n set<int> set1(nums1.begin(), nums1.end());\n set<int> set2(nums2.begin(), nums2.end());\n \n vector<int> diff1, diff2;\n for(int num : set1)\n if(set2.find(num) == set2.end())\n diff1.push_back(num);\n \n for(int num : set2)\n if(set1.find(num) == set1.end())\n diff2.push_back(num);\n \n return {diff1, diff2};\n }\n};\n```\n``` JavaScript []\n/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @return {number[][]}\n */\nvar findDifference = function(nums1, nums2) {\n let set1 = new Set(nums1);\n let set2 = new Set(nums2);\n\n let diff1 = [...set1].filter(x => !set2.has(x));\n let diff2 = [...set2].filter(x => !set1.has(x));\n\n return [diff1, diff2];\n};\n```\n``` C# []\npublic class Solution {\n public IList<IList<int>> FindDifference(int[] nums1, int[] nums2) {\n HashSet<int> set1 = new HashSet<int>(nums1);\n HashSet<int> set2 = new HashSet<int>(nums2);\n \n set1.ExceptWith(nums2);\n set2.ExceptWith(nums1);\n \n return new List<IList<int>> { set1.ToList(), set2.ToList() };\n }\n}\n```\n``` Java []\nclass Solution {\n public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {\n Set<Integer> set1 = Arrays.stream(nums1).boxed().collect(Collectors.toSet());\n Set<Integer> set2 = Arrays.stream(nums2).boxed().collect(Collectors.toSet());\n \n // Remove all elements from set1 that are present in set2\n set1.removeAll(Arrays.stream(nums2).boxed().collect(Collectors.toSet()));\n \n // Remove all elements from set2 that are present in set1\n set2.removeAll(Arrays.stream(nums1).boxed().collect(Collectors.toSet()));\n \n return Arrays.asList(new ArrayList<>(set1), new ArrayList<>(set2));\n }\n}\n```
16
0
['C++', 'Java', 'Python3', 'JavaScript', 'C#']
2
find-the-difference-of-two-arrays
C# | 1-Liner | Except
c-1-liner-except-by-dana-n-m2z9
Intuition\nThis question is really about set difference. The first thing that came to mind was the LINQ Except() method which does exactly what is being asked.\
dana-n
NORMAL
2023-05-03T03:06:20.777577+00:00
2024-09-15T18:17:40.576522+00:00
1,777
false
# Intuition\nThis question is really about set difference. The first thing that came to mind was the LINQ `Except()` method which does exactly what is being asked.\n\n# Approach\nUsing `Except()`, calculate both $$A - B$$ and $$B - A$$ and return the result in a 2-element array. \n\n# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```cs\npublic IList<IList<int>> FindDifference(int[] A, int[] B) =>\n \xA0 \xA0[\n \xA0 \xA0 \xA0 \xA0[..A.Except(B)],\n [..B.Except(A)]\n \xA0 \xA0];\n```\n \nCheck out my other C# 1-liners!\n\n - https://leetcode.com/discuss/general-discussion/2905237/c-sharp-1-liners\n
13
0
[]
0
find-the-difference-of-two-arrays
[C++] Find the Difference of Two Arrays using unordered_set
c-find-the-difference-of-two-arrays-usin-15dt
Thinking Process:\nAdd all elements of both array in a set.\nThen iterate through both array and using find() method, if the element is not found in other set,
prilily
NORMAL
2022-03-27T04:08:27.712826+00:00
2022-03-27T06:53:25.116935+00:00
2,084
false
**Thinking Process:**\nAdd all elements of both array in a set.\nThen iterate through both array and using find() method, if the element is not found in other set, add it to the answer.\nDo this for both the arrays and return the answer.\n\n```\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n\t//unordered_set is implemented using a hash table where keys are hashed into indices of a hash table\n\t// all operations take O(1) on average\n unordered_set<int> n1;\n unordered_set<int> n2;\n for(int i=0;i<nums1.size();i++)\n n1.insert(nums1[i]);\n \n for(int i=0;i<nums2.size();i++)\n n2.insert(nums2[i]);\n \n vector<int> ans1;\n\t\tvector<vector<int>> ans;\n for(int x:n1)\n {\n if(n2.find(x)==n2.end())\n ans1.push_back(x);\n }\n\t\tans.push_back(ans1);\n\t\tans1.clear();\n for(int x:n2)\n {\n if(n1.find(x)==n1.end())\n ans1.push_back(x);\n }\n ans.push_back(ans1);\n return ans;\n }\n};\n```\n**Time Complexity: O(n)**\n where n is max(n1,n2), for iterating through both arrays and adding elements to set.\n \n Edit: using a single array for holding the answer.
13
0
['C', 'Ordered Set']
3
find-the-difference-of-two-arrays
Easy Solution | Hashing | Better Approach
easy-solution-hashing-better-approach-by-q2i2
Intuition\nThe goal is to find elements that are unique to each of the two arrays. Using HashSet provides an efficient way to handle duplicates and perform memb
bkeshavbaskar
NORMAL
2024-11-28T03:21:00.430537+00:00
2024-11-28T03:21:00.430575+00:00
4,315
false
# Intuition\nThe goal is to find elements that are unique to each of the two arrays. Using `HashSet` provides an efficient way to handle duplicates and perform membership checks in constant average time complexity.\n\n- The problem boils down to finding elements that are **only in `nums1`** and elements that are **only in `nums2`**.\n- By leveraging `HashSet`, we can efficiently find these differences while avoiding duplicates in the result.\n\n---\n\n# Approach\n1. **Convert Arrays to HashSets**:\n - Add all elements of `nums1` to `h1` and all elements of `nums2` to `h2`.\n - This removes any duplicates within each array.\n\n2. **Identify Common Elements**:\n - Iterate through one of the arrays (`nums2`) and check if the element exists in `h1`.\n - If an element is found in both sets, remove it from both `h1` and `h2` to ensure it\'s excluded from the final result.\n\n3. **Build the Result**:\n - The remaining elements in `h1` are unique to `nums1`, and the remaining elements in `h2` are unique to `nums2`.\n - Convert these sets to lists and return them as part of a nested list.\n\n---\n\n# Complexity\n\n- **Time Complexity**: \n $$O(n + m)$$ \n - \\(O(n)\\) to populate `h1` with elements from `nums1`. \n - \\(O(m)\\) to populate `h2` with elements from `nums2`. \n - Iterating through `nums2` and performing membership checks/removals is \\(O(m)\\) on average. \n\n- **Space Complexity**: \n $$O(n + m)$$ \n - Storage for `h1` and `h2` to hold all unique elements from `nums1` and `nums2`.\n\n---\n\n# Code\n\n### Java\n```java\nimport java.util.*;\n\nclass Solution {\n public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {\n // Initialize sets for both arrays\n HashSet<Integer> h1 = new HashSet<>();\n HashSet<Integer> h2 = new HashSet<>();\n \n // Populate the sets\n for (int n : nums1) h1.add(n);\n for (int n : nums2) h2.add(n);\n\n // Remove common elements from both sets\n for (int n : nums2) {\n if (h1.contains(n)) {\n h1.remove(n);\n h2.remove(n);\n }\n }\n\n // Build the result\n List<List<Integer>> result = new ArrayList<>();\n result.add(new ArrayList<>(h1)); // Unique to nums1\n result.add(new ArrayList<>(h2)); // Unique to nums2\n \n return result;\n }\n}\n```\n\n### Python\n```python\nclass Solution:\n def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:\n # Convert arrays to sets\n h1 = set(nums1)\n h2 = set(nums2)\n\n # Remove common elements\n for num in nums2:\n if num in h1:\n h1.remove(num)\n h2.discard(num)\n\n # Return the remaining unique elements\n return [list(h1), list(h2)]\n\n```\n### CPP\n```cpp\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n // Use unordered_set to store unique elements\n unordered_set<int> h1(nums1.begin(), nums1.end());\n unordered_set<int> h2(nums2.begin(), nums2.end());\n\n // Remove common elements\n for (int num : nums2) {\n if (h1.find(num) != h1.end()) {\n h1.erase(num);\n h2.erase(num);\n }\n }\n\n // Build and return the result\n return {vector<int>(h1.begin(), h1.end()), vector<int>(h2.begin(), h2.end())};\n }\n};\n\n```\n\n### Javascript\n```js\nvar findDifference = function(nums1, nums2) {\n // Convert arrays to sets\n const h1 = new Set(nums1);\n const h2 = new Set(nums2);\n\n // Remove common elements\n for (let num of nums2) {\n if (h1.has(num)) {\n h1.delete(num);\n h2.delete(num);\n }\n }\n\n // Convert sets to arrays and return\n return [Array.from(h1), Array.from(h2)];\n};\n```\n
12
0
['Array', 'Hash Table', 'C++', 'Java', 'Python3', 'JavaScript']
4
find-the-difference-of-two-arrays
Basic Set Operations || 96% Beats || Easy to Understand
basic-set-operations-96-beats-easy-to-un-ts5w
Intuition\n Describe your first thoughts on how to solve this problem. \nAs we have to find distinct numbers we can use set data structure.\n# Approach\n Descri
sivaram001
NORMAL
2024-02-01T16:38:21.245935+00:00
2024-02-15T06:20:31.305761+00:00
1,537
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAs we have to find ***distinct*** numbers we can use ***set*** ***data*** ***structure***.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**method1** Set Operations\nHere we have used basic set operations.\n\n**method2** Hashing\nIterated over the lsit and added to set and append the distinct elements to the answer.\n\nHope you get this or comment for any clarification.\n\nAnd all set:)\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(len(nums1) + len(nums2))\n\n# Code\n```\nclass Solution:\n def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:\n set1 = set(nums1)\n set2 = set(nums2)\n\n difference1 = list(set1 - set2)\n difference2 = list(set2 - set1)\n\n answer = [difference1, difference2]\n\n\n return answer\n```\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n1 + n2)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(len(nums1) + len(nums2))\n# Code\n```\nclass Solution:\n def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:\n set1 = set(nums1)\n set2 = set(nums2)\n answer = []\n\n l = set()\n\n for i in nums1:\n if i not in set2:\n l.add(i)\n answer.append(l)\n\n l = set()\n\n for i in nums2:\n if i not in set1:\n l.add(i)\n answer.append(l)\n\n return answer\n```\n\n\n\n\n
11
0
['Hash Table', 'Python3']
3
find-the-difference-of-two-arrays
🔥97% ✅Beats | | 🚀only using HashSet 🧠 | | 💚Friendly🙌
97-beats-only-using-hashset-friendly-by-ntpq1
\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n### 1. Create HashSets:\n Create two HashSet objects (s1 and s2) to store the uniq
Pintu008
NORMAL
2023-12-11T10:07:58.944086+00:00
2023-12-11T10:07:58.944113+00:00
745
false
\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n### 1. Create HashSets:\n Create two HashSet objects (s1 and s2) to store the unique elements of nums1 and nums2, respectively.\n\n### 2. Populate HashSets:\n Iterate through each element of nums1 and nums2 and add them to the corresponding HashSet.\n\n### 3. Create Lists from HashSets: \nCreate two ArrayList objects (lst1 and lst2) by converting the elements of s1 and s2 to lists.\n\n### 4. Find the Symmetric Difference: \nUse the removeAll method to find the symmetric difference. lst1.removeAll(s2) removes all elements from lst1 that are also present in s2, and lst2.removeAll(s1) removes all elements from lst2 that are also present in s1.\n\n### 5. Create Result List: \nCreate a list (lst) to store the two lists representing the symmetric difference. Add lst1 and lst2 to lst.\n\n### 6. Return Result:\n Return the final list lst as the result.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: **O(N+M)**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\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 HashSet<Integer> s1 = new HashSet<>();\n HashSet<Integer> s2 = new HashSet<>();\n \n for(int ele : nums1){\n s1.add(ele); \n }\n for(int ele : nums2){\n s2.add(ele);\n }\n \n List<List<Integer>> lst = new ArrayList<>();\n List<Integer> lst1 = new ArrayList<>(s1);\n List<Integer> lst2 = new ArrayList<>(s2);\n lst1.removeAll(s2);\n lst2.removeAll(s1);\n lst.add(lst1);\n lst.add(lst2);\n return lst;\n }\n}\n```\n![WhatsApp Image 2023-12-03 at 12.33.52.jpeg](https://assets.leetcode.com/users/images/30f541d2-a01d-4bbc-8281-bd8acfb6b866_1702288914.4701035.jpeg)\n
11
0
['Array', 'Hash Table', 'Java']
2
find-the-difference-of-two-arrays
❤️Easy Solution in 🔥C++,🔥JAVA,🔥Python||❤️Daily Leetcode solution
easy-solution-in-cjavapythondaily-leetco-qyp7
Please upVote \u2764\uFE0F\n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time complexity:O(nlogn)\n Add your time complexit
skumarsingh
NORMAL
2023-05-03T02:50:58.913417+00:00
2023-05-03T04:06:35.219728+00:00
2,296
false
# Please upVote \u2764\uFE0F\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n```C++ []\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n vector<vector<int>> ans(2);\n set<int> st1(nums1.begin(), nums1.end());\n set<int> st2(nums2.begin(), nums2.end());\n set_difference(st1.begin(), st1.end(), st2.begin(), st2.end(), back_inserter(ans[0]));\n set_difference(st2.begin(), st2.end(), st1.begin(), st1.end(), back_inserter(ans[1]));\n return ans;\n }\n};\n```\n```Java []\npublic class Solution {\n public static List<List<Integer>> findDifference(List<Integer> nums1, List<Integer> nums2) {\n List<List<Integer>> ans = new ArrayList<>(2);\n Set<Integer> st1 = new HashSet<>(nums1);\n Set<Integer> st2 = new HashSet<>(nums2);\n List<Integer> temp = new ArrayList<>();\n List<Integer> temp1 = new ArrayList<>();\n for (int x : st1) {\n if (!st2.contains(x)) {\n temp.add(x);\n }\n }\n for (int x : st2) {\n if (!st1.contains(x)) {\n temp1.add(x);\n }\n }\n ans.add(temp);\n ans.add(temp1);\n return ans;\n }\n}\n```\n```python []\ndef findDifference(nums1: List[int], nums2: List[int]) -> List[List[int]]:\n ans = [[], []]\n st1 = set(nums1)\n st2 = set(nums2)\n ans[0] = list(st1 - st2)\n ans[1] = list(st2 - st1)\n return ans\n```\n\n\n# C++ second Code\n```\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n vector<vector<int>> ans;\n set<int> st1;\n set<int> st2;\n for(auto x: nums1)\n {\n st1.insert(x);\n }\n for(auto x: nums2)\n {\n st2.insert(x);\n }\n vector<int> temp;\n vector<int> temp1;\n for(auto x:st1)\n {\n if(st2.find(x)==st2.end())\n {\n temp.push_back(x);\n }\n }\n for(auto x:st2)\n {\n if(st1.find(x)==st1.end())\n {\n temp1.push_back(x);\n }\n }\n ans.push_back(temp);\n ans.push_back(temp1);\n return ans;\n }\n};\n```\n# c++ third code\n```\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n vector<vector<int>> ans(2);\n unordered_set<int> set1(nums1.begin(), nums1.end());\n unordered_set<int> set2(nums2.begin(), nums2.end());\n for (int num : set1) {\n if (set2.find(num) == set2.end()) {\n ans[0].push_back(num);\n }\n }\n for (int num : set2) {\n if (set1.find(num) == set1.end()) {\n ans[1].push_back(num);\n }\n }\n return ans;\n }\n};\n```\n\n# Please upVote \u2764\uFE0F
11
0
['C++']
0
find-the-difference-of-two-arrays
java HashSet straightforward
java-hashset-straightforward-by-jstm2022-70y4
\nclass Solution {\n public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {\n Set<Integer> s1 = new HashSet<Integer>();\n Set<In
JSTM2022
NORMAL
2022-03-27T04:05:15.083092+00:00
2022-03-27T04:05:15.083122+00:00
1,330
false
```\nclass Solution {\n public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {\n Set<Integer> s1 = new HashSet<Integer>();\n Set<Integer> s2 = new HashSet<Integer>();\n \n for(int i : nums1){\n s1.add(i);\n }\n for(int i : nums2){\n s2.add(i);\n }\n List<List<Integer>> ret = new ArrayList();\n ret.add(new ArrayList());\n ret.add(new ArrayList());\n for(int i : s1){\n if(!s2.contains(i)){\n ret.get(0).add(i);\n }\n }\n for(int i : s2){\n if(!s1.contains(i)){\n ret.get(1).add(i);\n }\n }\n \n return ret;\n }\n}\n```
11
0
['Java']
1
find-the-difference-of-two-arrays
🏆 Easy to understand |⚡ Optimal O(N + M) | 🚀 Clean & Efficient
easy-to-understand-optimal-on-m-clean-ef-cdhq
🔹 Intuition & Approach 🔹💡 Think of it as a "difference filter"! We need to find numbers that are unique in nums1 and nums2, meaning they appear in one but not i
himanshu7437
NORMAL
2025-03-08T19:40:44.336408+00:00
2025-03-08T19:40:44.336408+00:00
1,123
false
### **🔹 Intuition & Approach 🔹** 💡 **Think of it as a "difference filter"!** We need to find numbers that are **unique** in `nums1` and `nums2`, meaning they appear in one but **not** in the other. --- ### **🚀 Steps to Solve:** 1️⃣ **Store all unique numbers in sets** → 📦 `set1` for `nums1`, 📦 `set2` for `nums2`. 2️⃣ **Find elements in `set1` but not in `set2`** → 🧐 If `set2` **doesn’t contain** a number from `set1`, add it to the answer! 3️⃣ **Find elements in `set2` but not in `set1`** → Same process as step 2. 4️⃣ **Return both lists as a single answer!** ✅ --- ### **📌 Example for Better Understanding:** #### **Input:** ```java nums1 = [1, 2, 3, 3] nums2 = [2, 4, 6] ``` #### **Steps:** - `set1` → `{1, 2, 3}` ✅ (removes duplicate `3`) - `set2` → `{2, 4, 6}` ✅ - Elements **in `set1` but not in `set2`** → `{1, 3}` ➝ `[1, 3]` - Elements **in `set2` but not in `set1`** → `{4, 6}` ➝ `[4, 6]` #### **Output:** ```java [[1, 3], [4, 6]] ``` --- ### **⏱️ Time & Space Complexity:** #### **⏳ Time Complexity:** - **Adding elements to `HashSet`** → `O(N + M)` - **Checking for distinct elements** → `O(N + M)` - **Overall Complexity** → **O(N + M) ✅ (Most Optimal Solution)** #### **🗂️ Space Complexity:** - **Two HashSets (`set1` & `set2`)** → `O(N + M)` - **Two result lists (`list1` & `list2`)** → `O(N + M)` - **Overall Complexity** → **O(N + M) ✅** --- ### **🌟 Why Use `HashSet`?** ⚡ **Fast Lookup (`O(1)`)** → Checking if an element exists is super quick! 🚀 **Removes duplicates automatically** → No extra work needed! 🎯 **Optimized for large inputs** → No unnecessary loops! --- # Code ```java [] class Solution { public List<List<Integer>> findDifference(int[] nums1, int[] nums2) { // Use HashSets to store unique elements from both arrays Set<Integer> set1 = new HashSet<>(); Set<Integer> set2 = new HashSet<>(); // Populate set1 with elements from nums1 for (int num : nums1) { set1.add(num); } // Populate set2 with elements from nums2 for (int num : nums2) { set2.add(num); } // Lists to store elements that are unique to each array List<Integer> list1 = new ArrayList<>(); List<Integer> list2 = new ArrayList<>(); // Find elements in set1 that are NOT in set2 for (int num : set1) { if (!set2.contains(num)) { list1.add(num); } } // Find elements in set2 that are NOT in set1 for (int num : set2) { if (!set1.contains(num)) { list2.add(num); } } // Return the two lists as a single result return Arrays.asList(list1, list2); } } ``` ``` python [] class Solution: def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]: set1, set2 = set(nums1), set(nums2) list1 = [num for num in set1 if num not in set2] list2 = [num for num in set2 if num not in set1] return [list1, list2] ``` ``` cpp [] class Solution { public: vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) { 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}; } }; ``` ![upvote.jpg](https://assets.leetcode.com/users/images/e71dfccb-bdfe-4602-bf42-387e13c53c0d_1741462372.0380337.jpeg)
10
0
['Array', 'Hash Table', 'Hash Function', 'Java']
1
find-the-difference-of-two-arrays
c solution
c-solution-by-nameldi-ig3k
\nint** findDifference(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize, int** returnColumnSizes){\n /* range -1000 - 1000, 2001 totally
nameldi
NORMAL
2022-06-11T00:44:43.543125+00:00
2023-05-03T01:50:21.694557+00:00
954
false
```\nint** findDifference(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize, int** returnColumnSizes){\n /* range -1000 - 1000, 2001 totally */\n int* hash = (int*)calloc(2001, sizeof(int));\n int** ans = (int**)malloc(sizeof(int*) * 2);\n ans[0] = (int*)calloc(nums1Size, sizeof(int));\n ans[1] = (int*)calloc(nums2Size, sizeof(int));\n \n for(int i = 0; i < nums2Size; i++)\n hash[nums2[i]+1000] = 1;\n \n for(int i = 0; i < nums1Size; i++)\n {\n if(hash[nums1[i]+1000]>0)/* means both num1 and num2 existed */\n hash[nums1[i]+1000]++;\n else /* only num1 has */\n hash[nums1[i]+1000] = -1;\n }\n int* col = (int*)calloc(2, sizeof(int));\n for(int i = -1000; i <= 1000; i++)\n {\n if(hash[i+1000] == -1)/* num1 */\n ans[0][col[0]++] = i;\n else if(hash[i+1000] == 1)/* num2 */\n ans[1][col[1]++] = i;\n }\n \n *returnSize = 2;\n *returnColumnSizes = col;\n return ans;\n}\n```
10
0
['C']
1
find-the-difference-of-two-arrays
Easy Solution using Set with explanation|| O(n+m)
easy-solution-using-set-with-explanation-cpch
Intuition\nAs it is mentioned that we need to find distinct integers, frequency of the elements doesnot matter. Hence we can use HashSets over here, to store th
ishita_das
NORMAL
2023-05-03T06:41:39.924429+00:00
2023-05-03T06:45:30.825491+00:00
2,229
false
# Intuition\nAs it is mentioned that we need to find distinct integers, frequency of the elements doesnot matter. Hence we can use HashSets over here, to store the distinct elements of each array. To get nums1-nums2 elements, need to store elements of nums1 in hashSet and remove elements which are present in nums2.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nNeed two hashSet for: (1) Integers present in nums1, but not in nums2, (2) Integers present in nums2, but not in nums1. Below steps to be followed:\n1. Iterate over nums1 and Store distinct elements of nums1 in set1.\n2. Iterate over nums2 and remove elements from set1, if exists.\n3. Iterate over nums2 and Store distinct elements of nums2 in set2.\n4. Iterate over nums1 and remove elements from set2, if exists.\nNow, look closely, step 2 and 3, both are iterating in nums2, so we can combine the loop.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n+m)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n+m)\n\n# Code\nPLEASE UPVOTE IF YOU LIKE.\n\n```\n\nclass Solution {\n public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {\n HashSet<Integer> set1 = new HashSet<Integer>();\n HashSet<Integer> set2 = new HashSet<Integer>();\n List<List<Integer>> ans=new ArrayList<List<Integer>>();\n\n //iterate over nums1 and store distinct elements in set1\n for(int i=0;i<nums1.length;i++)\n {\n set1.add(nums1[i]);\n }\n \n //Iterate over nums2 and store distinct elements in set2. \n //Also, remove matching elements of nums2 from set1\n for(int i=0;i<nums2.length;i++)\n {\n set2.add(nums2[i]);\n if(set1.contains(nums2[i]))\n set1.remove(nums2[i]);\n }\n\n // remove matching elements of nums1 from set2\n for(int i=0;i<nums1.length;i++)\n {\n if(set2.contains(nums1[i]))\n set2.remove(nums1[i]);\n }\n\n //convert set1 and set2 to answer arrayList\n ans.add(new ArrayList<Integer>(set1));\n ans.add(new ArrayList<Integer>(set2));\n return ans;\n }\n}\n```
9
0
['Java']
2
find-the-difference-of-two-arrays
Python3🔥🔥|leetcodeChallengeDay3 |python3 solution
python3leetcodechallengeday3-python3-sol-evhq
Intuition\n Describe your first thoughts on how to solve this problem. \n\nBy converting nums1 and nums2 to sets set1 and set2, we can easily find the set diffe
Kibreab-Teshome
NORMAL
2023-05-03T03:57:57.060683+00:00
2023-05-03T06:52:15.421695+00:00
3,280
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nBy converting nums1 and nums2 to sets set1 and set2, we can easily find the set differences between them\nThe resulting lists diff1 and diff2 contain the elements that are present in nums1 but not in nums2, and vice versa.\nBy creating a list of lists result with diff1 and diff2 as its elements, we can return both sets of elements as required by the problem statement.\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can convert the input arrays nums1 and nums2 to sets set1 and set2, respectively\nWe can then find the set difference between set1 and set2 to get the elements that are in set1 but not in set2\nSimilarly, we can find the set difference between set2 and set1 to get the elements that are in set2 but not in set1\nWe can then create a list of lists result with diff1 and diff2 as its elements, and return result.\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 set1,set2=set(nums1),set(nums2)\n return[list(set1-set2),list(set2-set1)]\n\n#other possible answer for this problem is\nclass Solution:\n def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:\n set1=set(nums1)\n set2=set(nums2)\n res=[[],[]]\n\n for i in set1:\n if i not in set2:\n res[0].append(i)\n for i in set2:\n if i not in set1:\n res[1].append(i)\n return res\n\n#other possible answer for this problem\nclass Solution:\n def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:\n set1,set2=set(nums1),set(nums2)\n return[set1-set2,set2-set1]\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n```
9
0
['Python3']
1
find-the-difference-of-two-arrays
2 Lines of Code LOL, Beats 90% too :)
2-lines-of-code-lol-beats-90-too-by-nick-gv4b
Intuition\n Describe your first thoughts on how to solve this problem. \nLet\'s simply use set operations to do this. Convert both nums1 and nums2 into their re
NickieChmikie
NORMAL
2024-05-02T01:08:24.386322+00:00
2024-05-02T01:08:24.386341+00:00
1,104
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nLet\'s simply use set operations to do this. Convert both nums1 and nums2 into their respective sets, and return their set difference, in the form of a list. As simple that!\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Convert into the two sets: ```set1, set2```\n- Take the set difference of both ```list(set1 - set2)``` and ```list(set2 - set1)``` and cast it as a list (since that is what we need to return)\n- Return!\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n# Code\n```\nclass Solution:\n def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:\n set1, set2 = set(nums1), set(nums2)\n return [list(set1 - set2), list(set2 - set1)]\n```
8
0
['Python3']
2
find-the-difference-of-two-arrays
Simple Solution using Arrays without sets 🌐✨
simple-solution-using-arrays-without-set-o1i5
Intuition\nSince the constraints guarantee a range from -1000 to 1000, I decided to use a vector with an offset of 2001 to cleverly represent these values.\n\n#
sambhav22435
NORMAL
2024-01-30T11:23:26.866501+00:00
2024-01-30T11:23:26.866530+00:00
3,092
false
# Intuition\nSince the constraints guarantee a range from -1000 to 1000, I decided to use a vector with an offset of 2001 to cleverly represent these values.\n\n# Approach\nTo tackle the problem, I decided to use this vector as a mark to indicate the presence of a particular value. I traversed both `nums1` and `nums2` to mark the values encountered by setting the corresponding index in the vector to 1. After marking, I checked for unique values in each array. If a value was found to be unique in either array, I added it to the answer vector and marked it as used.\n\nI also threw in a bit of humor by mentioning the "people using each other" metaphor when marking the values as -1 after they were added to the result vectors.\n\n# Complexity\n- Time complexity: $$O(n)$$, where $$n$$ is the size of the larger array among `nums1` and `nums2`. The loops to mark and find unique values contribute to this linear time complexity.\n- Space complexity: $$O(1)$$, considering the vector size is constant (2001). The extra space used is reasonable and does not scale with the input size, thanks to the clever indexing.\n# Contribution\n\n- I only wrote the code in c++ all other language codes are generated by `chatgpt`.\n- It also helped me in generating the explanation from my broken english.\n- Thanks ...................................................\n# Code\n``` cpp []\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n nums1.reserve(1e4); // just to avoid overflow\n nums2.reserve(1e4); // you can also reserve like 1000 + 2001 = 3001\n \n // By seeing constraints we can confirm the least value that we will get is -1000 .\n // and the max we will get is 1000.\n // so to reprent -1000 on a vector index we have to add an offset of 2001\n // mark nums[nums[0]] =1 for value we have encountered.\n // after that in both arrays index check if the value if present only in one array\n // then push to the answer vector.\n\n for(int i =0;i<nums1.size();i++){\n nums1[nums1[i]+2001] = 1; \n }\n\n \n for(int i =0;i<nums2.size();i++){\n nums2[nums2[i]+2001] = 1; \n }\n\n vector<int> first;\n vector<int> sec;\n for(int i =0;i<nums1.size();i++){\n if(nums1[nums1[i]+2001] == 1 and nums2[nums1[i]+2001] !=1) {\n first.push_back(nums1[i]);\n nums1[nums1[i]+2001] = -1; // indicating we have used this value like people use each other \n }\n }\n for(int i =0;i<nums2.size();i++){\n if(nums2[nums2[i]+2001] == 1 and nums1[nums2[i]+2001] !=1) {\n sec.push_back(nums2[i]);\n nums2[nums2[i] +2001] =-1; \n }\n }\n return {first,sec};\n }\n};\n```\n``` java []\nimport java.util.ArrayList;\nimport java.util.List;\n\nclass Solution {\n public List<List<Integer>> findDifference(List<Integer> nums1, List<Integer> nums2) {\n List<List<Integer>> result = new ArrayList<>();\n List<Integer> first = new ArrayList<>();\n List<Integer> sec = new ArrayList<>();\n \n for (int i = 0; i < 1e4; i++) {\n nums1.add(0);\n nums2.add(0);\n }\n\n for (int i = 0; i < nums1.size(); i++) {\n nums1.set(nums1.get(i) + 2001, 1);\n }\n\n for (int i = 0; i < nums2.size(); i++) {\n nums2.set(nums2.get(i) + 2001, 1);\n }\n\n for (int i = 0; i < nums1.size(); i++) {\n if (nums1.get(nums1.get(i) + 2001) == 1 && nums2.get(nums1.get(i) + 2001) != 1) {\n first.add(nums1.get(i));\n nums1.set(nums1.get(i) + 2001, -1);\n }\n }\n\n for (int i = 0; i < nums2.size(); i++) {\n if (nums2.get(nums2.get(i) + 2001) == 1 && nums1.get(nums2.get(i) + 2001) != 1) {\n sec.add(nums2.get(i));\n nums2.set(nums2.get(i) + 2001, -1);\n }\n }\n\n result.add(first);\n result.add(sec);\n return result;\n }\n}\n\n\n```\n``` c []\n#include <stdio.h>\n#include <stdlib.h>\n\nstruct Solution {\n int* findDifference(int* nums1, int* nums2, int nums1Size, int nums2Size) {\n int* result = (int*)malloc(2 * sizeof(int*));\n int* first = (int*)malloc(nums1Size * sizeof(int*));\n int* sec = (int*)malloc(nums2Size * sizeof(int*));\n\n for (int i = 0; i < 1e4; i++) {\n nums1 = realloc(nums1, (nums1Size + i) * sizeof(int));\n nums2 = realloc(nums2, (nums2Size + i) * sizeof(int));\n }\n\n for (int i = 0; i < nums1Size; i++) {\n nums1[nums1[i] + 2001] = 1;\n }\n\n for (int i = 0; i < nums2Size; i++) {\n nums2[nums2[i] + 2001] = 1;\n }\n\n int firstIndex = 0;\n int secIndex = 0;\n\n for (int i = 0; i < nums1Size; i++) {\n if (nums1[nums1[i] + 2001] == 1 && nums2[nums1[i] + 2001] != 1) {\n first[firstIndex++] = nums1[i];\n nums1[nums1[i] + 2001] = -1;\n }\n }\n\n for (int i = 0; i < nums2Size; i++) {\n if (nums2[nums2[i] + 2001] == 1 && nums1[nums2[i] + 2001] != 1) {\n sec[secIndex++] = nums2[i];\n nums2[nums2[i] + 2001] = -1;\n }\n }\n\n result[0] = first;\n result[1] = sec;\n return result;\n }\n};\n\n```\n``` javascript []\nclass Solution {\n findDifference(nums1, nums2) {\n nums1.length = 1e4;\n nums2.length = 1e4;\n const result = [[], []];\n\n for (let i = 0; i < nums1.length; i++) {\n nums1[nums1[i] + 2001] = 1;\n }\n\n for (let i = 0; i < nums2.length; i++) {\n nums2[nums2[i] + 2001] = 1;\n }\n\n for (let i = 0; i < nums1.length; i++) {\n if (nums1[nums1[i] + 2001] === 1 && nums2[nums1[i] + 2001] !== 1) {\n result[0].push(nums1[i]);\n nums1[nums1[i] + 2001] = -1;\n }\n }\n\n for (let i = 0; i < nums2.length; i++) {\n if (nums2[nums2[i] + 2001] === 1 && nums1[nums2[i] + 2001] !== 1) {\n result[1].push(nums2[i]);\n nums2[nums2[i] + 2001] = -1;\n }\n }\n\n return result;\n }\n}\n\n```\n\n``` python []\nclass Solution:\n def findDifference(self, nums1, nums2):\n nums1 += [0] * int(1e4)\n nums2 += [0] * int(1e4)\n result = [[], []]\n\n for i in range(len(nums1)):\n nums1[nums1[i] + 2001] = 1\n\n for i in range(len(nums2)):\n nums2[nums2[i] + 2001] = 1\n\n for i in range(len(nums1)):\n if nums1[nums1[i] + 2001] == 1 and nums2[nums1[i] + 2001] != 1:\n result[0].append(nums1[i])\n nums1[nums1[i] + 2001] = -1\n\n for i in range(len(nums2)):\n if nums2[nums2[i] + 2001] == 1 and nums1[nums2[i] + 2001] != 1:\n result[1].append(nums2[i])\n nums2[nums2[i] + 2001] = -1\n\n return result\n\n```\n``` Go []\npackage main\n\nimport "fmt"\n\ntype Solution struct{}\n\nfunc (sol *Solution) findDifference(nums1 []int, nums2 []int) [][]int {\n\tnums1 = append(nums1, make([]int, int(1e4))...)\n\tnums2 = append(nums2, make([]int, int(1e4))...)\n\tresult := [][]int{[]int{}, []int{}}\n\n\tfor i := 0; i < len(nums1); i++ {\n\t\tnums1[nums1[i]+2001] = 1\n\t}\n\n\tfor i := 0; i < len(nums2); i++ {\n\t\tnums2[nums2[i]+2001] = 1\n\t}\n\n\tfor i := 0; i < len(nums1); i++ {\n\t\tif nums1[nums1[i]+2001] == 1 && nums2[nums1[i]+2001] != 1 {\n\t\t\tresult[0] = append(result[0], nums1[i])\n\t\t\tnums1[nums1[i]+2001] = -1\n\t\t}\n\t}\n\n\tfor i := 0; i < len(nums2); i++ {\n\t\tif nums2[nums2[i]+2001] == 1 && nums1[nums2[i]+2001] != 1 {\n\t\t\tresult[1] = append(result[1], nums2[i])\n\t\t\tnums2[nums2[i]+2001] = -1\n\t\t}\n\t}\n\n\treturn result\n}\n\nfunc main() {\n\tsol := Solution{}\n\tnums1 := []int{1, 2, 3}\n\tnums2 := []int{2, 3, 4}\n\tresult := sol.findDifference(nums1, nums2)\n\tfmt.Println(result)\n}\n\n```\n\n![e9a5leu8hmhb1.jpg](https://assets.leetcode.com/users/images/d7c7cc4a-d50e-4955-99f7-29f948189864_1706613733.347077.jpeg)\n![nn5o2llpphha1.webp](https://assets.leetcode.com/users/images/2b8cc7b1-766e-438b-b55d-f9826cf2003b_1706613756.2279892.webp)\n
8
0
['Array', 'C', 'Python', 'C++', 'Java', 'Go', 'JavaScript']
3
find-the-difference-of-two-arrays
Without using set and array methods
without-using-set-and-array-methods-by-m-1xj0
\n\n# Code\n\n/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @return {number[][]}\n */\nvar findDifference = function (nums1, nums2) {\n let
malikdinar
NORMAL
2023-05-08T04:08:28.087320+00:00
2023-05-08T04:08:28.087349+00:00
923
false
\n\n# Code\n```\n/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @return {number[][]}\n */\nvar findDifference = function (nums1, nums2) {\n let arr1=[];\n let arr2=[];\n for (let i = 0; i < nums1.length; i++) {\n let flag=true;\n for (let j = 0, k=i+1; j < nums2.length+nums1.length; j++,k++) {\n if(nums1[i]===nums2[j] || nums1[i]==nums1[k]){\n flag=false;\n }\n }\n if(flag){\n arr1.push(nums1[i])\n }\n }\n for (let i = 0; i < nums2.length; i++) {\n let flag=true\n for (let j=0,k=i+1; j < nums1.length+nums2.length; j++,k++) {\n if(nums1[j]==nums2[i] || nums2[i]==nums2[k]){\n flag=false;\n }\n }\n if(flag===true){\n arr2.push(nums2[i])\n }\n }\n return [arr1,arr2]\n};\n```
8
0
['Array', 'JavaScript']
0
find-the-difference-of-two-arrays
Python 🐍 Solution Easy
python-solution-easy-by-souvik_banerjee-ce2l6
Intuition\n Describe your first thoughts on how to solve this problem. \nThis is a Python code for finding the difference between two lists. The function findDi
Souvik_Banerjee-2020
NORMAL
2023-05-03T12:47:36.122675+00:00
2023-05-03T12:47:36.122721+00:00
790
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis is a Python code for finding the difference between two lists. The function findDifference takes in two lists, nums1 and nums2, as its arguments. It first converts these lists into sets using the built-in set() function.\n\nThe set() function creates a set object from the given iterable (lists, tuples, strings, etc.). A set is an unordered collection of unique objects, so if there are any duplicates in either of the input lists, they will be removed during the conversion to sets.\n\nAfter converting the input lists to sets, the function uses the set difference operator (-) to find the difference between them. Specifically, it computes s1 - s2 and s2 - s1, which are the elements that are in s1 but not in s2, and vice versa, respectively. Finally, it returns the results as lists using the built-in list() function.\n\nNote that the returned list contains two sub-lists, one for each direction of the difference. If you only want the difference in one direction, you can simply return either list(s1 - s2) or list(s2 - s1) .\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach used in the findDifference function is to first convert the input lists nums1 and nums2 into sets s1 and s2, respectively. This is done using the built-in set() function in Python.\n\nAfter converting the input lists to sets, the function finds the set difference between the two sets using the set difference operator (-). This operator returns a new set that contains all elements in the left operand set (s1) that are not present in the right operand set (s2). It also returns a new set that contains all elements in the right operand set (s2) that are not present in the left operand set (s1).\n\nFinally, the function converts these two sets back to lists using the built-in list() function and returns them as a list of two sub-lists representing the difference in both directions.\n\nThe advantage of this approach is that it uses the built-in set operations in Python, which are optimized for efficiency. This results in a simple and efficient solution to find the difference between two lists without needing to write complex code for iterating over the lists and comparing their elements.\n# Complexity\n- Time complexity:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution(object):\n def findDifference(self, nums1, nums2):\n s1, s2 = set(nums1), set(nums2)\n return [list(s1 - s2), list(s2 - s1)]\n """\n :type nums1: List[int]\n :type nums2: List[int]\n :rtype: List[List[int]]\n """\n```\n\n
8
0
['Array', 'Hash Table', 'Python', 'Python3']
0
find-the-difference-of-two-arrays
TS/JS Hacks with efficient memory - beats 97.10%
tsjs-hacks-with-efficient-memory-beats-9-z6e7
\n# Code\n\nfunction findDifference(nums1: number[], nums2: number[]): number[][] {\n const len = Math.max(nums1.length, nums2.length)\n\n const [ans1, an
adiathasan
NORMAL
2023-05-03T08:54:20.252812+00:00
2023-05-03T08:54:38.456572+00:00
2,404
false
\n# Code\n```\nfunction findDifference(nums1: number[], nums2: number[]): number[][] {\n const len = Math.max(nums1.length, nums2.length)\n\n const [ans1, ans2] = [new Set<number>(), new Set<number>()]\n\n for(let i = 0; i < len; i++){\n if(nums1[i] !== undefined){\n if(!nums2.includes(nums1[i])){\n ans1.add(nums1[i])\n }\n }\n\n if(nums2[i] !== undefined){\n if(!nums1.includes(nums2[i])){\n ans2.add(nums2[i])\n }\n }\n }\n\n return [Array.from(ans1), Array.from(ans2)]\n};\n```
8
0
['TypeScript', 'JavaScript']
2
find-the-difference-of-two-arrays
Easy O(n) Python Solution (PLEASE UPVOTE)
easy-on-python-solution-please-upvote-by-qhry
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
baibhavsingh07
NORMAL
2023-05-03T04:28:19.977684+00:00
2023-05-03T17:11:54.521768+00:00
785
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- \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 s1 = set(nums1)\n s2 = set(nums2)\n return [list(s1-s2),list(s2-s1)]\n```
8
1
['Array', 'Python3']
0
find-the-difference-of-two-arrays
Swift😎
swift-by-upvotethispls-ipyj
Set Operations (accepted answer)\n\nclass Solution {\n func findDifference(_ p: [Int], _ q: [Int]) -> [[Int]] {\n [Set(p).subtracting(q), Set(q).subtr
UpvoteThisPls
NORMAL
2023-05-03T00:17:02.764380+00:00
2024-06-06T13:20:14.848820+00:00
483
false
**Set Operations (accepted answer)**\n```\nclass Solution {\n func findDifference(_ p: [Int], _ q: [Int]) -> [[Int]] {\n [Set(p).subtracting(q), Set(q).subtracting(p)].map(Array.init) \n }\n}\n\n```
8
0
['Swift']
2
find-the-difference-of-two-arrays
Easy solution using map in c++
easy-solution-using-map-in-c-by-aditya_k-4brx
Before moving to the solution let see why we have to use the map for this question.\nWe have to find the element that is present in the first array and the same
aditya_kumar_129
NORMAL
2022-10-07T07:32:08.415721+00:00
2022-10-08T06:09:03.554420+00:00
581
false
Before moving to the solution let see why we have to use the map for this question.\nWe have to find the element that is present in the first array and the same is not present in the second array.\nSimilarly for the second array also.\nWe can find this element using O(1) time complexity using map.\nNow the question came why we have to iterate the map and not the elements of the array while searching.\nWhen we iterate the array then there are situation in which we got the element that are present in the array more than once and hence it will be pushed more than once in the temp data structure.\nIn order to tackle this situation we will iterate the map rather than arrays.\n```\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n vector<vector<int>> ans;\n unordered_map<int,int> mp1,mp2;\n for(auto it : nums1) mp1[it]++;\n for(auto it : nums2) mp2[it]++;\n vector<int> temp;\n for(auto it : mp1){\n if(mp2.find(it.first) == mp2.end())\n temp.push_back(it.first);\n }\n ans.push_back(temp);\n temp.clear();\n for(auto it : mp2){\n if(mp1.find(it.first) == mp1.end())\n temp.push_back(it.first);\n }\n ans.push_back(temp);\n return ans;\n }\n};\n```\nIf you like this approach Please Upvote it.\nFeel free to ask any doubt
8
0
[]
2
find-the-difference-of-two-arrays
Python solution. Clean code with full comments. 95.96% speed.
python-solution-clean-code-with-full-com-118z
\nclass Solution:\n def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:\n \n set_1 = list_to_set(nums1)\n s
375d
NORMAL
2022-10-06T10:51:16.086432+00:00
2022-10-13T12:36:24.683436+00:00
2,737
false
```\nclass Solution:\n def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:\n \n set_1 = list_to_set(nums1)\n set_2 = list_to_set(nums2)\n \n return remove_same_elements(set_1, set_2)\n \n# Convert the lists into sets via helper method. \ndef list_to_set(arr: List[int]):\n \n s = set()\n \n for i in arr:\n s.add(i)\n \n return s \n\n# Now when the two lists are sets, use the difference attribute to filter common elements of the two sets.\ndef remove_same_elements(x, y):\n \n x, y = list(x - y), list(y - x)\n \n return [x, y]\n\n\n# Runtime: 185 ms, faster than 95.96% of Python3 online submissions for Find the Difference of Two Arrays.\n# Memory Usage: 14.3 MB, less than 51.66% of Python3 online submissions for Find the Difference of Two Arrays.\n\n# If you like my work, then I\'ll appreciate a like. Thanks!\n```
8
1
['Ordered Set', 'Python', 'Python3']
3
find-the-difference-of-two-arrays
[JS] Easy set find difference
js-easy-set-find-difference-by-casshsu-lzhi
\nvar findDifference = function(nums1, nums2) {\n const s1 = new Set(nums1);\n const s2 = new Set(nums2);\n \n const a1 = [...s1].filter(x => !s2.ha
casshsu
NORMAL
2022-03-30T14:36:51.512718+00:00
2022-03-30T14:36:51.512753+00:00
1,114
false
```\nvar findDifference = function(nums1, nums2) {\n const s1 = new Set(nums1);\n const s2 = new Set(nums2);\n \n const a1 = [...s1].filter(x => !s2.has(x));\n const a2 = [...s2].filter(x => !s1.has(x));\n \n return [a1, a2];\n};\n```
8
0
['Ordered Set', 'JavaScript']
2
find-the-difference-of-two-arrays
Most Easy Solution || Using Set
most-easy-solution-using-set-by-who-i-am-dcvy
Code
roniahamed
NORMAL
2025-01-31T05:39:13.362598+00:00
2025-01-31T05:39:13.362598+00:00
1,717
false
# Code ```python3 [] class Solution: def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]: a = set(nums1) - set(nums2) b = set(nums2) - set(nums1) li = [list(a),list(b)] return li ```
7
1
['Array', 'Ordered Set', 'Python', 'Python3']
1
find-the-difference-of-two-arrays
✅Simple Java Solutions
simple-java-solutions-by-ahmedna126-xl47
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
ahmedna126
NORMAL
2023-09-27T22:55:16.919176+00:00
2023-11-07T11:35:24.685870+00:00
738
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {\n List<List<Integer>> list = new LinkedList<>();\n list.add(find(nums1 , nums2));\n list.add(find(nums2 , nums1));\n return list;\n }\n\n public static List<Integer> find(int[] nums1, int[] nums2)\n {\n HashSet<Integer> set = new HashSet<>();\n for (int n : nums2) set.add(n);\n\n HashSet<Integer> list = new HashSet<>();\n\n for (int n1 : nums1 )\n {\n if (!set.contains(n1))\n {\n list.add(n1);\n }\n }\n return list.stream().toList();\n }\n}\n```\n## For additional problem-solving solutions, you can explore my repository on GitHub: [GitHub Repository](https://github.com/ahmedna126/java_leetcode_challenges)\n\n\n\n![abcd1.jpeg](https://assets.leetcode.com/users/images/29517929-81da-44a0-8eb2-91f7475408c1_1695855295.7307534.jpeg)\n\n\n
7
0
['Java']
1
find-the-difference-of-two-arrays
C++✅✅|| Easy Solution using Hashmap || #TryitHindi
c-easy-solution-using-hashmap-tryithindi-eb6q
Approach\n Describe your approach to solving the problem. \nDekho yrr simple si approach hai, pahle map me freq count karo and alternate arrays me check karlo j
kumarSaksham
NORMAL
2023-08-23T17:57:57.434002+00:00
2023-08-23T17:57:57.434035+00:00
250
false
# Approach\n<!-- Describe your approach to solving the problem. -->\nDekho yrr simple si approach hai, pahle map me freq count karo and alternate arrays me check karlo jiski count 0 wo tumhare kaam ka. \nAdd karo apne answer me and then return karo answer.\nHan ye dhyaan rahe ki repetitions avoid karne parenge.\nAchi lage to UPVOTE kardo.\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) \n {\n unordered_map<int, int>mpp1,mpp2;\n for(auto it: nums1)\n mpp1[it]++;\n for(auto it : nums2)\n mpp2[it]++;\n vector<vector<int>>answer(2);\n //check in nums1 if freq in mpp2 == 0, then push it to answer[0]\n //also set the mpp1[i]= -1 so that repetitions in nums1 do not count; \n for(auto i: nums1){\n if(mpp1[i]!=-1 && mpp2.count(i)==0)\n answer[0].push_back(i);\n mpp1[i]=-1;\n }\n for(auto i: nums2){\n if(mpp2[i]!=-1 && mpp1.count(i)==0)\n answer[1].push_back(i);\n mpp2[i]=-1;\n }\n\n return answer; \n }\n};\n```\n![upvote.jpg](https://assets.leetcode.com/users/images/9129e6fe-b220-4a8c-a049-c203b4879de6_1692813388.570648.jpeg)\n
7
0
['Array', 'Hash Table', 'C++']
1
find-the-difference-of-two-arrays
🚀 Golang fastest and clean solution (17ms, beats 100% by runtime)
golang-fastest-and-clean-solution-17ms-b-qv9b
Instead of map we can use an array in this problem because the range of possible values is very small [-1000, 1000]. Since we can\'t use negative numbers as arr
d9rs
NORMAL
2023-05-03T16:12:02.359764+00:00
2023-05-04T11:15:06.754655+00:00
1,085
false
Instead of `map` we can use an array in this problem because the range of possible values is very small `[-1000, 1000]`. Since we can\'t use negative numbers as array indexes, we\'ll just add 1000 to each number, so we have an index range of `[0, 2000]`.\n\nOtherwise, the logic is simple, we write to the dictionary array what numbers are in one set, and from the second set we select only those that are not in the dictionary array. This logic is implemented in the `setDifference` function, which essentially finds the set difference `A - B`.\n```go\nfunc setDifference(a, b []int) []int {\n d := [2001]bool{}\n ans := []int{}\n for _, x := range b {\n d[x + 1000] = true\n }\n for _, x := range a {\n if !d[x + 1000] {\n ans = append(ans, x)\n d[x + 1000] = true // prevent duplicates from being added\n }\n }\n return ans\n}\n\nfunc findDifference(nums1 []int, nums2 []int) [][]int {\n return [][]int{ setDifference(nums1, nums2), setDifference(nums2, nums1) }\n}\n```\nThe time complexity of this solution is O(n + m).
7
0
['Go']
0
find-the-difference-of-two-arrays
python3 Solution
python3-solution-by-motaharozzaman1996-t0zl
\n\nclass Solution:\n def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:\n n1=set(nums1)\n n2=set(nums2)\n
Motaharozzaman1996
NORMAL
2023-05-03T00:59:25.343629+00:00
2023-05-03T00:59:25.343666+00:00
4,839
false
\n```\nclass Solution:\n def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:\n n1=set(nums1)\n n2=set(nums2)\n r1=list(set(x for x in nums1 if x not in n2))\n r2=list(set(x for x in nums2 if x not in n1))\n return [r1,r2]\n```
7
0
['Python', 'Python3']
2
find-the-difference-of-two-arrays
Java Solution Using HashSet
java-solution-using-hashset-by-abhinav_0-nz0s
```\nclass Solution {\n public List> findDifference(int[] nums1, int[] nums2) {\n List> ans = new ArrayList<>();\n HashSet n1 = new HashSet<>()
Abhinav_0561
NORMAL
2022-10-02T08:52:56.657916+00:00
2022-10-02T09:23:03.614493+00:00
976
false
```\nclass Solution {\n public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {\n List<List<Integer>> ans = new ArrayList<>();\n HashSet<Integer> n1 = new HashSet<>();//Creating a hashset to check the unique elements present in the nums1\n HashSet<Integer> n2 = new HashSet<>();//Creating a hashset to check the unique elements present in the nums2\n for (int i = 0; i < nums1.length; i++) {\n n1.add(nums1[i]);\n }\n for (int i = 0; i < nums2.length; i++) {\n n2.add(nums2[i]);\n }\n HashSet<Integer> ans1 = new HashSet<>();\n for (int i = 0; i < nums2.length; i++) {\n if (!n1.contains(nums2[i])) ans1.add(nums2[i]);//Adding the unique ans into a hashset so that no number gets repeated\n }\n HashSet<Integer> ans2 = new HashSet<>();\n for (int i = 0; i < nums1.length; i++) {\n if (!n2.contains(nums1[i])) ans2.add(nums1[i]);//Adding the unique ans into a hashset so that no number gets repeated\n }\n\t\t//Making lists to enter the ans which is in hashset\n List<Integer> list1 = new ArrayList<>(ans1);\n List<Integer> list2 = new ArrayList<>(ans2);\n ans.add(list2);\n ans.add(list1);\n return ans;\n }\n}
7
0
['Java']
1
find-the-difference-of-two-arrays
Solution By Dare2Solve | Detailed Explanation | Clean Code
solution-by-dare2solve-detailed-explanat-kim9
Explanation []\nauthorslog.com/blog/RUbuPJtkxb\n\n# Code\n\ncpp []\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector
Dare2Solve
NORMAL
2024-08-18T18:04:11.476376+00:00
2024-08-18T18:04:11.476412+00:00
1,410
false
```Explanation []\nauthorslog.com/blog/RUbuPJtkxb\n```\n# Code\n\n```cpp []\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n set<int> set1(nums1.begin(), nums1.end());\n set<int> set2(nums2.begin(), nums2.end());\n\n vector<int> nums1Def;\n for (int n : set1) {\n if (set2.find(n) == set2.end()) {\n nums1Def.push_back(n);\n }\n }\n\n vector<int> nums2Def;\n for (int n : set2) {\n if (set1.find(n) == set1.end()) {\n nums2Def.push_back(n);\n }\n }\n\n return {nums1Def, nums2Def};\n }\n};\n```\n\n```python []\nclass Solution:\n def findDifference(self, nums1, nums2):\n set1 = set(nums1)\n set2 = set(nums2)\n\n nums1Def = [n for n in set1 if n not in set2]\n nums2Def = [n for n in set2 if n not in set1]\n\n return [nums1Def, nums2Def]\n```\n\n```java []\nclass Solution {\n public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {\n Set<Integer> set1 = new HashSet<>();\n for (int n : nums1) {\n set1.add(n);\n }\n\n Set<Integer> set2 = new HashSet<>();\n for (int n : nums2) {\n set2.add(n);\n }\n\n List<Integer> nums1Def = new ArrayList<>();\n for (int n : set1) {\n if (!set2.contains(n)) {\n nums1Def.add(n);\n }\n }\n\n List<Integer> nums2Def = new ArrayList<>();\n for (int n : set2) {\n if (!set1.contains(n)) {\n nums2Def.add(n);\n }\n }\n\n List<List<Integer>> result = new ArrayList<>();\n result.add(nums1Def);\n result.add(nums2Def);\n return result;\n }\n}\n```\n\n```javascript []\nvar findDifference = function (nums1, nums2) {\n let set1 = new Set(nums1)\n let set2 = new Set(nums2)\n\n const nums1Def = []\n for (let n of set1) {\n if (!set2.has(n)) nums1Def.push(n)\n }\n\n const nums2Def = []\n for (let n of set2) {\n if (!set1.has(n)) nums2Def.push(n)\n }\n return [nums1Def, nums2Def]\n};\n```
6
0
['Hash Table', 'Python', 'C++', 'Java', 'Python3', 'JavaScript']
1
find-the-difference-of-two-arrays
✅ ❤️ SUPER Easy Solution With Kotlin 🔥 JAVA 🔥 Using Set 🔥 Super Friendly 🔥
super-easy-solution-with-kotlin-java-usi-hnsv
Simple Solution \n\n\n\nJava []\npublic List<List<Integer>> findDifference(int[] nums1, int[] nums2) {\n\n Set<Integer> s1 = new HashSet(Arrays.asList(nums1)
sachin-worldnet
NORMAL
2023-05-03T14:46:34.348313+00:00
2023-05-10T20:29:52.137498+00:00
448
false
Simple Solution \n\n\n\n```Java []\npublic List<List<Integer>> findDifference(int[] nums1, int[] nums2) {\n\n Set<Integer> s1 = new HashSet(Arrays.asList(nums1));\n Set<Integer> s2 = new HashSet(Arrays.asList(nums2));\n\n ArrayList<Integer> nums1Distinct = new ArrayList<>();\n\n for(int num: s1){\n if(!s2.contains(num)){\n nums1Distinct.add(num);\n }else{\n s2.remove(num);\n }\n }\n return Arrays.asList(nums1Distinct, new ArrayList<>(s2));\n}\n```\n```Kotlin []\nclass Solution {\n fun findDifference(nums1: IntArray, nums2: IntArray): List<List<Int>> {\n val s1 = nums1.toMutableSet()\n val s2 = nums2.toMutableSet()\n val nums1Distinct = arrayListOf<Int>()\n\n s1.forEach{\n if(!s2.contains(it))\n nums1Distinct.add(it)\n else{\n s2.remove(it)\n }\n }\n return listOf(nums1Distinct, s2.toList())\n }\n}\n```\n\n\n# Intuition\n- We aim to find the difference between two arrays and return the result in the form of two lists.\n- To accomplish this, we can convert both input arrays into `Sets` to remove duplicates, and then iterate over one `Set` to check if each element is present in the other `Set`.\n- If an element is present in the other `Set`, we remove it from that `Set`.\n- If an element is not present in the other `Set`, we add it to a result `List`.\n\n---\n\n\n# Approach\n1. Start by initializing two mutable sets, `s1` and `s2`, to represent the unique elements of `nums1` and `nums2`, respectively.\n- Initialize an empty `ArrayList`, `nums1Distinct`, to store the elements that are present in `s1` but not in `s2` *(Avoid utilizing unncessory memory)*.\n3. Iterate over the elements in `s1`, and for each element:\n * Check if `s1` element is present in `s2`.\n * If it is present in `s2`, remove it from `s2`. ***(This is why we don\'t need additional array for distinct element for `nums2`)***\n * If it is not present in `s2`, add it to `nums1Distinct`.\n4. Finally, return the result as a list containing `nums1Distinct` and the remaining elements of `s2` converted to a `list`.\n\n---\n\n\n\n# Complexity\n- ## Time complexity: $$O(n)$$\n1. Initializing two mutable sets `s1` and `s2 ->`$$O(n)$$, where n is the length of `nums1` or `nums2`.\n2. Initializing an empty array list `n1 ->`$$O(n)$$.\n3. Iterating over the elements in `s1 ->`$$O(n)$$.\n4. For each element, checking if it is present in `s2 ->`$$O(n)$$ on average for `HashSet`.\n5. If the element is present in `s2`, removing it from `s2 ->`$$O(n)$$ on average for `HashSet`.\n6. If the element is not present in `s2`, adding it to `n1 ->`$$O(n)$$.\n7. Converting `s2` to a `list ->`$$O(n)$$.\n8. Returning the result as a list containing `n1` and the remaining elements of `s2 ->`$$O(n)$$.\n\nTherefore, the overall time complexity of this algorithm is $$O(n)$$, where $$n$$ is the length of `nums1` or `nums2`.\n\n- ## Space complexity: $$O(n)$$\nThe space complexity of this algorithm is also linear to the size of the input arrays. There are three data structures that use space:\n\n1. `s1` and `s2` are mutable sets that store the distinct elements of `nums1` and `nums2` respectively. The space used by each set is proportional to the number of distinct elements in the corresponding input array. In the worst case, when all elements in the input arrays are unique, the size of each set will be $$n$$, where $$n$$ is the length of the input arrays. Therefore, the space used by both sets combined is $$O(n)$$.\n2. `nums1Distinct` is an `ArrayList` that stores the elements that are present in `s1` but not in `s2`. The space used by this `list` is proportional to the number of elements that are unique to nums1, which is at most $$n$$. Therefore, the space used by `nums1Distinct` is also $$O(n)$$.\n3. The output list contains two lists, `nums1Distinct` and the remaining elements of `s2`. As discussed earlier, the combined size of these two lists is at most $$n$$. Therefore, the space used by the output list is also $$O(n)$$.\nTherefore, the overall space complexity of this algorithm is $$O(n)$$.\n\n\n---\n\n\n## Conclusion\nIn summary, this algorithm finds the difference of two `arrays` and returns the result as two `lists` of distinct elements. It achieves a time complexity of $$O(n)$$ and a space complexity of $$O(n)$$. The solution is simple and intuitive, leveraging the built-in data structure `HashSet` in `Kotlin` and `Java` to efficiently **remove** duplicates and check `Set` membership.\n\n---\n\n\n## \u2764\uFE0F Happy Coding \u2764\uFE0F\n\n## Please UpVote \uD83D\uDC4D\n\n\n\n---\n\n\n
6
0
['Array', 'Hash Table', 'Two Pointers', 'Java', 'Kotlin']
0
find-the-difference-of-two-arrays
Java. Set. Find the Difference of Two Arrays
java-set-find-the-difference-of-two-arra-welf
\n\nclass Solution {\n public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {\n Set<Integer> one = Arrays.stream(nums1).boxed().collect
red_planet
NORMAL
2023-05-03T13:18:32.237283+00:00
2023-05-06T08:19:58.809012+00:00
1,145
false
\n```\nclass Solution {\n public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {\n Set<Integer> one = Arrays.stream(nums1).boxed().collect(Collectors.toSet());\n Set<Integer> two = Arrays.stream(nums2).boxed().collect(Collectors.toSet());\n Set<Integer> oneCopy = new HashSet<>(one);\n List<List<Integer>> answ = new ArrayList<>();\n one.removeAll(two);\n two.removeAll(oneCopy);\n\n answ.add(new ArrayList<>(one));\n answ.add(new ArrayList<>(two));\n return answ;\n }\n}\n```
6
0
['Java']
2
find-the-difference-of-two-arrays
Java || Runtime 10 ms Beats 93.56% Memory 43.6 MB Beats 29.55%
java-runtime-10-ms-beats-9356-memory-436-c343
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
Akash2023
NORMAL
2023-05-03T04:01:22.008746+00:00
2023-05-03T04:01:22.008788+00:00
1,299
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public 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 }\n for (int num : nums2) {\n set2.add(num);\n }\n List<Integer> diff1 = new ArrayList<>(set1);\n diff1.removeAll(set2);\n List<Integer> diff2 = new ArrayList<>(set2);\n diff2.removeAll(set1);\n List<List<Integer>> result = new ArrayList<>();\n result.add(diff1);\n result.add(diff2);\n return result;\n }\n}\n```
6
0
['Java']
2
find-the-difference-of-two-arrays
HashSet | Beginners approach | Java solution
hashset-beginners-approach-java-solution-ceb3
Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n)\n Add your space complexity here, e.g. O(n) \n\n# C
Akash-Sardar
NORMAL
2023-05-03T03:05:40.097513+00:00
2023-05-03T03:05:40.097540+00:00
836
false
# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {\n\n Set<Integer> set1=new HashSet<>();\n Set<Integer> set2=new HashSet<>();\n List<Integer> list1=new ArrayList<>();\n List<Integer> list2=new ArrayList<>();\n List<List<Integer>> ans=new ArrayList<>();\n\n for(int e: nums1) set1.add(e);\n for(int e: nums2) set2.add(e);\n\n for(int e: set1) if(!set2.contains(e)) list1.add(e);\n for(int e: set2) if(!set1.contains(e)) list2.add(e);\n\n ans.add(list1);\n ans.add(list2);\n\n return ans;\n }\n}\n```
6
0
['Java']
2
find-the-difference-of-two-arrays
2215 | c++ | Easy O(nlogn) solution | 2 approaches
2215-c-easy-onlogn-solution-2-approaches-e82l
Approach-1: Use sets to find difference\n\nTC: O(nlogn), SC: O(1)\n\nCode:\n\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& num
Yash2arma
NORMAL
2022-03-28T04:38:47.032564+00:00
2022-04-03T04:50:10.257334+00:00
1,486
false
**Approach-1:** Use sets to find difference\n\n**TC: O(nlogn), SC: O(1)**\n\n**Code:**\n```\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n \n set<int> s1, s2;\n \n for(auto it:nums1)\n s1.insert(it);\n \n for(auto it:nums2)\n s2.insert(it);\n \n vector<vector<int>> ans(2);\n \n for(auto it : s1)\n {\n if(s2.count(it) == 0)\n ans[0].push_back(it);\n }\n \n for(auto it : s2)\n {\n if(s1.count(it) == 0)\n ans[1].push_back(it);\n }\n \n return ans;\n }\n};\n```\n\n**Approach-1:** Use find operation to get the difference of two arrays\n\n**TC: O(n^2), SC: O(1)**\n\n**Code:**\n```\nclass Solution {\npublic:\n vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n \n vector<vector<int>> ans(2);\n \n //ans[0]: nums1-nums2\n for(int i=0; i<nums1.size(); i++)\n {\n if (find(nums2.begin(), nums2.end(), nums1[i]) == nums2.end() && find(ans[0].begin(), ans[0].end(), nums1[i])==ans[0].end())\n \n ans[0].push_back(nums1[i]);\n }\n \n \n //ans[1]: nums2-nums1\n for(int i=0; i<nums2.size(); i++)\n {\n if (find(nums1.begin(), nums1.end(), nums2[i]) == nums1.end() && find(ans[1].begin(), ans[1].end(), nums2[i])== ans[1].end())\n \n ans[1].push_back(nums2[i]);\n }\n \n return ans;\n }\n};\n```
6
0
['C', 'Ordered Set']
3
find-the-difference-of-two-arrays
Rust solution
rust-solution-by-bigmih-ysp9
\nimpl Solution {\n pub fn find_difference(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<Vec<i32>> {\n let idx = |x: i32| -> usize { (x + 1000) as _ };\n
BigMih
NORMAL
2022-03-27T08:24:33.141392+00:00
2022-03-27T08:24:33.141417+00:00
370
false
```\nimpl Solution {\n pub fn find_difference(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<Vec<i32>> {\n let idx = |x: i32| -> usize { (x + 1000) as _ };\n let mut counter = [0_u8; 2001];\n nums1.iter().for_each(|&x| counter[idx(x)] |= 0b01);\n nums2.iter().for_each(|&x| counter[idx(x)] |= 0b10);\n\n let mut res = vec![Vec::new(), Vec::new()];\n counter.iter().enumerate().for_each(|(i, &x)| match x {\n 0b01 => res[0].push(i as i32 - 1000),\n 0b10 => res[1].push(i as i32 - 1000),\n _ => (),\n });\n res\n }\n}\n```
6
0
['Bit Manipulation', 'Rust']
1
find-the-difference-of-two-arrays
EASY PYTHON SOLUTION
easy-python-solution-by-harsh_5191-kf69
Optimized Python SolutionExplanation✅Uses set operations for efficiency set1 - set2gives elements innums1but not innums2. set2 - set1gives elements innums2but n
harsh_5191
NORMAL
2025-02-23T05:42:00.791707+00:00
2025-02-23T05:42:00.791707+00:00
603
false
### **Optimized Python Solution** ```python class Solution(object): def findDifference(self, nums1, nums2): set1, set2 = set(nums1), set(nums2) # Convert lists to sets for O(1) lookups return [list(set1 - set2), list(set2 - set1)] # Compute differences and convert back to lists ``` --- ### **Explanation** ✅ **Uses set operations for efficiency** - `set1 - set2` gives elements in `nums1` but not in `nums2`. - `set2 - set1` gives elements in `nums2` but not in `nums1`. ✅ **Time Complexity: `O(n + m)`** - `set()` conversion takes `O(n)` and `O(m)`. - Subtraction (`set1 - set2`) takes `O(min(n, m))`. - Overall, this is highly efficient. ✅ **Space Complexity: `O(n + m)`** - Stores unique elements in sets. This is the most optimized solution! 🚀 ![b108d001-cf15-4ff7-847d-0497b3becd90.webp](https://assets.leetcode.com/users/images/e3987950-94a4-467e-a4aa-34745b3b456b_1740289231.9390483.webp)
5
0
['Python']
0
find-the-difference-of-two-arrays
100% beat | 2 Solutions | Array | Set |
100-beat-2-solutions-array-set-by-mcihan-7nzg
\n# Time Complexity\n Both of solutions are: O(n) \n\n# Code\n\n## 1- Array Solution\n\n100% Beats\n\n\nclass Solution {\n public List<List<Integer>> findD
mcihan7
NORMAL
2023-12-30T10:32:27.473652+00:00
2023-12-30T10:32:27.473671+00:00
1,006
false
\n# Time Complexity\n Both of solutions are: $$O(n)$$ \n\n# Code\n\n## 1- Array Solution\n\n100% Beats\n\n```\nclass Solution {\n public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {\n boolean[] n1 = new boolean[2001];\n boolean[] n2 = new boolean[2001];\n\n ArrayList<Integer> dif1 = new ArrayList<>();\n ArrayList<Integer> dif2 = new ArrayList<>();\n\n for (int num : nums1) {\n n1[num + 1000] = true;\n }\n\n for (int num : nums2) {\n n2[num + 1000] = true;\n\n if (!n1[num + 1000]) {\n n1[num + 1000] = true; // to avoid duplications\n dif2.add(num);\n }\n }\n\n for (int num : nums1) {\n if (!n2[num + 1000]) {\n n2[num + 1000] = true; // to avoid duplications\n dif1.add(num);\n }\n }\n\n return List.of(dif1, dif2);\n }\n}\n```\n\n## 2- Set Solution\n\n\n~68% Beats\n\n```\nclass Solution {\n public List<List<Integer>> findDifference(int[] nums1, int[] nums2){\n HashSet<Integer> set1 = new HashSet<>();\n HashSet<Integer> set2 = new HashSet<>();\n ArrayList<Integer> diff1 = new ArrayList<>();\n ArrayList<Integer> diff2 = new ArrayList<>();\n\n\n for (int i : nums1) {\n set1.add(i);\n }\n\n for (int i : nums2) {\n set2.add(i);\n if (set1.add(i)) {\n diff2.add(i);\n }\n }\n\n for (int i : nums1) {\n if (set2.add(i)) {\n diff1.add(i);\n }\n }\n\n return List.of(diff1, diff2);\n }\n}\n```\n\n<br/>\n\n \n\n<img src="https://assets.leetcode.com/users/images/085853ae-9586-479f-acf2-ec3ce30fd0e7_1703932262.0024223.png" style="width:400px;height:auto;">\n\n\n<br/>\n<br/>\n \n
5
0
['Java']
0
find-the-difference-of-two-arrays
🚀🔥Easy Solution🚀🙌 | | 💯98% ✅Green Beats🧠
easy-solution-98-green-beats-by-pintu008-46oa
\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n### 1. Initialize HashSet:\n\nCreate two HashSet objects (s1 and s2).\n### 2. Popu
Pintu008
NORMAL
2023-12-08T12:51:20.640364+00:00
2023-12-08T12:51:20.640386+00:00
84
false
\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n### 1. Initialize HashSet:\n\nCreate two HashSet objects (s1 and s2).\n### 2. Populate HashSets:\n\nIterate through nums1 and nums2, adding elements to s1 and s2, respectively.\n### 3. Initialize List of Lists:\n\nCreate a List of Lists (lst) to store the results.\n### 4. Create Inner Lists:\n\nCreate two inner lists (lst1 and lst2) from s1 and s2 using the ArrayList constructor.\n### 5. Find Differences:\n\nUse the removeAll method to find the elements that are present in lst1 but not in s2, and the elements present in lst2 but not in s1.\n### 6. Add Inner Lists to Result List:\n\nAdd the modified inner lists (lst1 and lst2) to the result list (lst).\n### 7. Return Result List:\n\nReturn the result list containing the differences between nums1 and nums2.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: **O(N*M)**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: **O(N)**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {\n HashSet<Integer> s1 = new HashSet<>();\n HashSet<Integer> s2 = new HashSet<>();\n \n for(int ele : nums1){\n s1.add(ele); \n }\n for(int ele : nums2){\n s2.add(ele);\n }\n \n List<List<Integer>> lst = new ArrayList<>();\n List<Integer> lst1 = new ArrayList<>(s1);\n List<Integer> lst2 = new ArrayList<>(s2);\n lst1.removeAll(s2);\n lst2.removeAll(s1);\n lst.add(lst1);\n lst.add(lst2);\n return lst;\n }\n}\n```\n![WhatsApp Image 2023-12-03 at 12.33.52.jpeg](https://assets.leetcode.com/users/images/14bca837-6731-4327-90cf-1bbabd20c07d_1702039760.9552104.jpeg)\n
5
0
['Hash Table', 'Java']
0