Search code examples
javaarraysarraylistunionarray-merge

Union of two array, but time complexity is the issue


Multiple solutions available online for union of arrays, I came up with one of my own which is working fine but again it has significant time complexities (which I obviously don't know). So in order to use similar logic in a better way I am asking here. Any suggestion would be great!

Initially there are two arrayList with different sizes and numbers in it.

  1. First step is to append both of them in a single List
  2. Second step is to sort the new array using Collections.sort() method.
  3. Third is to use .remove() to remove the duplicates from it. Below is the code

//initial two arrays

array1[0, 2, 3, 4, 5] and array2[0, 1, 2, 3, 5, 7, 8]

//for loop to append them in one arrayList and sort

for(k = 0; k< array1.size();k++){
    array3.add(array1.get(k));
}
for(k = 0; k< array2.size();k++){
    array3.add(array2.get(k));
}
Collections.sort(array3);

//Now removing the duplicates

for(k=0; k<array3.size();k++){
    if(k != array3.size()-1){
       if(Objects.equals(array3.get(k), array3.get(k + 1))){
       array3.remove(k);
     }
   }
}

Solution

  • IntStream.distinct

    You can use distinct() operation, which maintains a LinkedHashSet under the hood to guarantee uniqueness of elements and preserve their order, to obtain the union of the given arrays:

    int[] array1 = {0, 2, 3, 4, 5};
    int[] array2 = {0, 1, 2, 3, 5, 7, 8};
            
    int[] union = IntStream
        .concat(Arrays.stream(array1), Arrays.stream(array2))
        .distinct().toArray();
            
    System.out.println(Arrays.toString(union));
    

    Output:

    [0, 2, 3, 4, 5, 1, 7, 8]