# 350. Intersection of Two Arrays II

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-MgAy9dy1enq-sTej7s-%2F-MgB2KKHIm2xgQg0psp-%2Fimage.png?alt=media\&token=54ce0460-732a-42b2-bea5-32d1f5da3c1c)

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

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-MgBAK7jQdwSfP1kjms7%2F-MgBBWclBL4tGov7L6o2%2Fimage.png?alt=media\&token=2fa1cb58-a673-4f00-ac63-192fd8ceb2bb)

#### 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();
    }

}
```
