LeetCode – Intersection of Two Arrays (Java)

Given two arrays, write a function to compute their intersection.

Java Solution 1 - HashSet

Time = O(n).
Space = O(n).

public int[] intersection(int[] nums1, int[] nums2) {
    HashSet<Integer> set1 = new HashSet<Integer>();
    for(int i: nums1){
    HashSet<Integer> set2 = new HashSet<Integer>();
    for(int i: nums2){
    int[] result = new int[set2.size()];
    int i=0;
    for(int n: set2){
        result[i++] = n;
    return result;

Java Solution 2 - Binary Search

Time = O(nlog(n)).
Space = O(n).

public int[] intersection(int[] nums1, int[] nums2) {
    ArrayList<Integer> list = new ArrayList<Integer>();
    for(int i=0; i<nums1.length; i++){
        if(i==0 || (i>0 && nums1[i]!=nums1[i-1])){
            if(Arrays.binarySearch(nums2, nums1[i])>-1){
    int[] result = new int[list.size()];
    int k=0;
    for(int i: list){
        result[k++] = i;
    return result;

Any improvement?

Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";
  • Cong Wang

    requirement: the output contains unique values.

  • rokyslash

    Both the programs are wrong. They dont work for inputs [1,2,2,1], [2,2]. The expected output in this case would be [2,2] but your programs only output [2].

  • Zevgon

    I think there might be another possible improvement. Not positive, but here’s what I’m thinking:

    Sort the shorter array, then iterate through the longer array, doing a modified bsearch on the sorted array for each element. Keep track of the indices in the sorted array that have already been used, and pass that set into the modified bsearch as invalid indices.

    I think that would be time complexity of O(mlog(n)), a little better than O(nlog(n) + mlog(m)). I think potentially worse space complexity of 2n because of keeping track of the invalid indices, but still O(n).

  • strmrdr

    I believe the time complexity for the binary search method is a much more than O(nlog(n)) considering that it takes that time just to sort a single array- you are sorting two arrays and then performing a binary search on every element of one of the arrays.

  • Praveen Singh

    try to get the intersection between below arrays using binary search –
    int[] arr1 = {7, 18, 24, 32, 44, 57, 40, 22, 8, 38};
    int[] arr2 = {8, 0, 29, 9, 18};

    I tried, But 18 is not coming in intersection.

  • ryanlr

    Code changed. Thanks!

  • Anusha

    Yes, what you can do in set two is, without adding all the elements, add the ones that are present in the array1. Less space, and you don’t have to call iter.remove(); a slight performance optimization