Daily LeetCode Problems: Problem 2215. Find the Difference of Two Arrays
Introduction
In this article, we will discuss LeetCode problem 2215 “Find the Difference of Two Arrays”. We will look at the problem statement, its constraints, and its approach to solving the problem. We will also discuss the pseudocode, time complexity, and space complexity of our solution.
Problem Statement
The problem statement is as follows:
Given two integer arrays arr1
and arr2
, return the difference between the maximum value of arr2
and the minimum value of arr1
.
Constraints
- 1 <= arr1.length, arr2.length <= 1000
- -10⁹ <= arr1[i], arr2[i] <= 10⁹
Approach
The solution to this problem is simple. We can use the built-in functions min
and max
to find the minimum value of arr1
and the maximum value of arr2
, respectively. We can then subtract the minimum value of arr1
from the maximum value of arr2
and return the result.
Pseudocode
Here is the pseudocode for our solution:
function findDifference(arr1, arr2):
min_arr1 = min(arr1)
max_arr2 = max(arr2)
return max_arr2 - min_arr1
Time Complexity
The time complexity of our solution is O(n), where n is the length of the larger array between arr1
and arr2
. This is because we need to loop through the larger array to find the maximum value of arr2
and the minimum value of arr1
.
Space Complexity
The space complexity of our solution is O(1), since we only need to store the minimum value of arr1
and the maximum value of arr2
in two variables.
Complete Solution
Here is the complete solution to the problem:
Python
class Solution:
def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:
set1 = set(nums1)
set2 = set(nums2)
return [set1 - set2, set2 - set1]
C++
class Solution {
public:
vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {
vector<vector<int>> ans(2);
unordered_set<int> set1{begin(nums1), end(nums1)};
unordered_set<int> set2{begin(nums2), end(nums2)};
for (const int num : set1)
if (!set2.count(num))
ans[0].push_back(num);
for (const int num : set2)
if (!set1.count(num))
ans[1].push_back(num);
return ans;
}
};
Java
class Solution {
public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {
Set<Integer> set1 = Arrays.stream(nums1).boxed().collect(Collectors.toSet());
Set<Integer> set2 = Arrays.stream(nums2).boxed().collect(Collectors.toSet());
Arrays.stream(nums1).forEach(set2::remove);
Arrays.stream(nums2).forEach(set1::remove);
return Arrays.asList(new ArrayList<>(set1), new ArrayList<>(set2));
}
}
Conclusion
In this article, we have discussed LeetCode problem 2215 “Find the Difference of Two Arrays”. We have looked at the problem statement, its constraints, and its approach to solving the problem. We have also discussed the pseudocode, time complexity, and space complexity of our solution. Finally, we have provided the complete solution to the problem in Python, Java and C++.
For more than 390 solutions, click here.