DDSA Solutions

Union of Arrays with Duplicates

Time: O(n+m)
Space: O(n+m)
Advertisement

Intuition

Find union of two arrays (all unique elements from both). HashSet approach.

Algorithm

  1. 1Add all elements from both arrays to a set. Size of set is the union count.

Common Pitfalls

  • O(m+n). Return count of distinct elements across both arrays. Output sorted union.
Union of Arrays with Duplicates.java
Java
// Approach: HashSet of all elements from both arrays, return its size.
// Time: O(n+m) Space: O(n+m)
import java.util.*;

class Solution {
    public static int findUnion(int a[], int b[]) {
        Set<Integer> set = new HashSet<>();
        for (int ele : a)
            set.add(ele);
        for (int ele : b)
            set.add(ele);

        return set.size();
    }
}

class Solution1 {
    public static ArrayList<Integer> findUnion(int[] a, int[] b) {
        Set<Integer> set = new HashSet<>();
        for (int ele : a)
            set.add(ele);
        for (int ele : b)
            set.add(ele);

        return new ArrayList<Integer>(set);
    }
}
Advertisement
Was this solution helpful?