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

}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://timmybeeflin.gitbook.io/cracking-leetcode/hashtable/350.-intersection-of-two-arrays-ii.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
