350. Intersection of Two Arrays II

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.
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

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

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

}

Last updated