349. Intersection of Two Arrays LeetCode Solution

In this guide, you will get 349. Intersection of Two Arrays LeetCode Solution with the best time and space complexity. The solution to Intersection of Two Arrays problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Intersection of Two Arrays solution in C++
  4. Intersection of Two Arrays solution in Java
  5. Intersection of Two Arrays solution in Python
  6. Additional Resources
349. Intersection of Two ArraysLeetCode Solution image

Problem Statement of Intersection of Two Arrays

Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]
Explanation: [4,9] is also accepted.

Constraints:

1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 1000

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(n)

349. Intersection of Two Arrays LeetCode Solution in C++

class Solution {
 public:
  vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
    vector<int> ans;
    unordered_set<int> set{nums1.begin(), nums1.end()};

    for (const int num : nums2)
      if (set.erase(num))
        ans.push_back(num);

    return ans;
  }
};
/* code provided by PROGIEZ */

349. Intersection of Two Arrays LeetCode Solution in Java

class Solution {
  public int[] intersection(int[] nums1, int[] nums2) {
    List<Integer> ans = new ArrayList<>();
    Set<Integer> set = Arrays.stream(nums1).boxed().collect(Collectors.toSet());

    for (final int num : nums2)
      if (set.remove(num))
        ans.add(num);

    return ans.stream().mapToInt(Integer::intValue).toArray();
  }
}
// code provided by PROGIEZ

349. Intersection of Two Arrays LeetCode Solution in Python

class Solution:
  def intersection(self, nums1: list[int], nums2: list[int]) -> list[int]:
    ans = []
    nums1 = set(nums1)

    for num in nums2:
      if num in nums1:
        ans.append(num)
        nums1.remove(num)

    return ans
 # code by PROGIEZ

Additional Resources

See also  413. Arithmetic Slices LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.