LeetCode 350: Intersection of Two Arrays II Solution
Master LeetCode problem 350 (Intersection of Two Arrays II), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
350. Intersection of Two Arrays II
Problem Explanation
Explanation
To find the intersection of two arrays, we can use a hashmap to store the frequency of elements in one of the arrays. Then, we iterate through the second array and decrement the frequency in the hashmap whenever we find a common element. We add this element to the result array. By doing this, we ensure that each element appears as many times as it shows in both arrays.
Algorithm:
- Create a hashmap to store the frequency of elements in
nums1. - Iterate through
nums1and populate the hashmap. - Iterate through
nums2:- If the element is found in the hashmap and its frequency is greater than 0, add it to the result array and decrement its frequency in the hashmap.
- Return the result array.
Time Complexity:
The time complexity of this approach is O(m + n) where m and n are the lengths of nums1 and nums2 respectively.
Space Complexity:
The space complexity is O(min(m, n)) where m and n are the lengths of nums1 and nums2 respectively.
Solution Code
import java.util.*;
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
Map<Integer, Integer> map = new HashMap<>();
List<Integer> result = new ArrayList<>();
for (int num : nums1) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
for (int num : nums2) {
if (map.containsKey(num) && map.get(num) > 0) {
result.add(num);
map.put(num, map.get(num) - 1);
}
}
int[] resArray = new int[result.size()];
for (int i = 0; i < result.size(); i++) {
resArray[i] = result.get(i);
}
return resArray;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 350 (Intersection of Two Arrays II)?
This page provides optimized solutions for LeetCode problem 350 (Intersection of Two Arrays II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 350 (Intersection of Two Arrays II)?
The time complexity for LeetCode 350 (Intersection of Two Arrays II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 350 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 350 in Java, C++, or Python.