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";
  • 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