Java Array Program · A28
Union of Two Sorted Arrays in Java
Walk both sorted arrays at once, always taking the smaller front value. Skip a value if it equals the last one you added.
Problem Statement
Given two arrays sorted in ascending order, return their union: every value that appears in either array, each once, in ascending order.
Either array may contain repeats or be empty.
Input/Output Examples
[1, 3, 3, 7] and [2, 3, 8]Output[1, 2, 3, 7, 8]Explanation: 3 appears three times in total but once in the union.[] and [4, 4]Output[4]Explanation: repeats inside one array are removed too.[5] and [5]Output[5]Explanation: the shared value appears once.Visual Explanation
- 1 vs 2result1take 1 from A
- 3 vs 2result12take 2 from B
- 3 vs 3result123take 3; later 3s are skipped last added = 3
- Restresult123787 from A, 8 from B
- Done[1, 2, 3, 7, 8]
[1, 3, 3, 7] and [2, 3, 8]: the smaller front value is taken each time, and a value equal to the last added one is skipped.Because both inputs are sorted, equal values reach the front together or one right after another. Comparing with the last added value is therefore enough to remove every repeat.
Approaches
The two-pointer merge uses the sorted order. The TreeSet version ignores it and sorts again.
Approach 1: Two-Pointer Merge (Recommended)
Idea: merge the arrays like merge sort, appending a value only if it differs from the last value added.
- While either array has values left, pick the smaller front value (or the only one left).
- Advance the pointer of the array it came from.
- Append it unless it equals the last value in the result.
Time: O(n + m) · Space: O(n + m). For the result.
Approach 2: TreeSet
Idea: add every value of both arrays to a TreeSet, which removes repeats and sorts.
- Add all values of both arrays to a
TreeSet. - Copy the set into a list.
Time: O((n + m) log(n + m)) · Space: O(n + m).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Two-Pointer Merge (Recommended)
One loop handles both arrays and the leftovers, so there are no separate tail loops.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class UnionTwoPointers {
// Merge like merge sort, appending a value only if it differs from the last one added
static List<Integer> union(int[] a, int[] b) {
List<Integer> result = new ArrayList<>();
int i = 0;
int j = 0;
while (i < a.length || j < b.length) {
int next;
if (j == b.length || (i < a.length && a[i] <= b[j])) {
next = a[i++];
} else {
next = b[j++];
}
if (result.isEmpty() || result.get(result.size() - 1) != next) {
result.add(next);
}
}
return result;
}
public static void main(String[] args) {
int[][][] pairs = {{{1, 3, 3, 7}, {2, 3, 8}}, {{}, {4, 4}}, {{5}, {5}}};
for (int[][] p : pairs) {
System.out.println(Arrays.toString(p[0]) + ", " + Arrays.toString(p[1]) + " -> " + union(p[0], p[1]));
}
}
}
[1, 3, 3, 7], [2, 3, 8] -> [1, 2, 3, 7, 8] [], [4, 4] -> [4] [5], [5] -> [5]
Time complexity: O(n + m) · Space complexity: O(n + m).
Approach 2: TreeSet
Short and works for unsorted input too, but it does not take advantage of the sorted order.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.TreeSet;
public class UnionTreeSet {
// A TreeSet removes repeats and keeps the values sorted
static List<Integer> union(int[] a, int[] b) {
TreeSet<Integer> set = new TreeSet<>();
for (int v : a) {
set.add(v);
}
for (int v : b) {
set.add(v);
}
return new ArrayList<>(set);
}
public static void main(String[] args) {
int[][][] pairs = {{{1, 3, 3, 7}, {2, 3, 8}}, {{}, {4, 4}}, {{5}, {5}}};
for (int[][] p : pairs) {
System.out.println(Arrays.toString(p[0]) + ", " + Arrays.toString(p[1]) + " -> " + union(p[0], p[1]));
}
}
}
[1, 3, 3, 7], [2, 3, 8] -> [1, 2, 3, 7, 8] [], [4, 4] -> [4] [5], [5] -> [5]
Time complexity: O((n + m) log(n + m)) · Space complexity: O(n + m).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Two-Pointer Merge | O(n + m) | O(n + m) |
| TreeSet | O((n + m) log(n + m)) | O(n + m) |
Here n and m are the array lengths. The merge reads each element once; the tree set pays a logarithmic cost per insertion.
Interview Tips and Recommended Approach
- Use the sorted order. It is what makes a linear solution possible.
- Handle repeats within one array. Comparing with the last added value covers them.
- Know the intersection variant. Advance both pointers only when the values are equal.
- Watch the boxed comparison. Comparing an
Integerfrom a list with anintunboxes it, which is safe.
Recommended Approach: Two-Pointer Merge
Why: it reads each array once, keeps the result sorted and removes duplicates without any extra data structure.