LeetCode 349: Intersection of Two Arrays Solution
Master LeetCode problem 349 (Intersection of Two Arrays), 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.
349. Intersection of Two Arrays
Problem Explanation
Explanation
To find the intersection of two arrays, we can use a set to store unique elements of one array and then iterate through the other array to check for common elements. We can use a set to ensure uniqueness of elements in the result.
- Create a set
set1to store unique elements ofnums1. - Iterate through
nums2and check if the element exists inset1. If it does, add it to the result set. - Convert the result set to an array and return it.
Time complexity: O(n + m) where n and m are the lengths of the two input arrays.
Space complexity: O(min(n, m)) where n and m are the lengths of the two input arrays.
Solution Code
import java.util.HashSet;
import java.util.Set;
import java.util.Arrays;
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<>();
for (int num : nums1) {
set1.add(num);
}
Set<Integer> resultSet = new HashSet<>();
for (int num : nums2) {
if (set1.contains(num)) {
resultSet.add(num);
}
}
int[] result = new int[resultSet.size()];
int index = 0;
for (int num : resultSet) {
result[index++] = num;
}
return result;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 349 (Intersection of Two Arrays)?
This page provides optimized solutions for LeetCode problem 349 (Intersection of Two Arrays) 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 349 (Intersection of Two Arrays)?
The time complexity for LeetCode 349 (Intersection of Two Arrays) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 349 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 349 in Java, C++, or Python.