> For the complete documentation index, see [llms.txt](https://timmybeeflin.gitbook.io/cracking-leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://timmybeeflin.gitbook.io/cracking-leetcode/hashtable/350.-intersection-of-two-arrays-ii.md).

# 350. Intersection of Two Arrays II

![](/files/-MgB2KKHIm2xgQg0psp-)

time: O(n+m)

space: O(min(n,m))

#### use hashmap in smaller array size one

```
It's a good idea to check array sizes and use a hash map for the smaller array. 
It will reduce memory usage when one of the arrays is very large.
```

```java
class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        List<Integer> res = new ArrayList<>();
        Map<Integer, Integer> map = new HashMap<>();
        
        for (int num : nums1) {
            map.put(num, map.getOrDefault(num, 0)+1);
        }
        for (int num : nums2) {
            if (map.containsKey(num)) {
                res.add(num);
                int count = map.get(num)-1;
                if (count == 0) {
                    map.remove(num);
                } else {
                    map.put(num, count);
                }
                
            }
        }
        return res.stream().mapToInt(n -> n).toArray();
    }

}
```

## follow up

![](/files/-MgBBWclBL4tGov7L6o2)

#### if sorted, compare each other

in this way, you can reduce the memory usage (for huge data, this one dont need HashMap

Time Complexity: O(nlogn+mlogm), where nn and mm are the lengths of the arrays. We sort two arrays independently, and then do a linear scan.

Space Complexity: from O(logn+logm) to O(n+m), depending on the implementation of the sorting algorithm

```java
class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        List<Integer> res = new ArrayList<>();
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        
        int i = 0, j = 0;
        while (i < nums1.length && j < nums2.length) { // O(m+n)
            if (nums1[i] < nums2[j]) {
                i++;
            } else if (nums1[i] > nums2[j]) {
                j++;
            } else {
                res.add(nums1[i]);
                i++;
                j++;
            }
        }
        return res.stream().mapToInt(n -> n).toArray();
    }

}
```
