Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Given two Set<String> a and b, write code to compute their union, intersection and difference without modifying a or b.

Copy one set into a new set and then call the bulk method on the copy: new HashSet<>(a) followed by addAll(b) gives the union, retainAll(b) gives the intersection, and removeAll(b) gives the difference a minus b. The copy is required because addAll, retainAll and removeAll change the set they are called on. For large sets, the intersection is cheaper if we iterate the smaller set and look each element up in the larger one.

Why this question is asked

Union, intersection and difference come up constantly in real code: which users are in both segments, which ids arrived today but not yesterday, which permissions does a role add. The Set interface has bulk methods for all three, but they share a trap that has caused many production bugs: they mutate the receiver. Interviewers ask this small coding question to see whether we know that, and whether we think about the cost when the sets are large. In this answer, we will recap the three operations, see the bug that happens without a copy, write the correct code, look at how the bulk methods work inside, and make the intersection efficient for large inputs.

1A Quick Recap of the Three Operations

A set holds each element at most once. The union of a and b holds every element that is in a, in b, or in both. The intersection holds only the elements that are in both. The difference a minus b holds the elements of a that are not in b; note that b minus a is a different set.

Java's Set interface expresses these with three bulk methods inherited from Collection. addAll(c) adds every element of c, retainAll(c) keeps only the elements that c also contains, and removeAll(c) removes every element that c contains. Each returns a boolean saying whether the set changed. None of them returns a new set: they all modify the set we call them on.

2The Bug: Calling the Bulk Methods Directly

Here is the version that looks natural and is wrong. We want the intersection, so we call retainAll on a.

Java
Set<String> a = new HashSet<>(Set.of("apple", "banana", "cherry"));
Set<String> b = new HashSet<>(Set.of("banana", "cherry", "date"));
Set<String> common = a; // just another reference to the same object
common.retainAll(b); // returns true: a was changed
System.out.println(common); // [banana, cherry] (order may vary)
System.out.println(a); // [banana, cherry] a has lost "apple"!

Notice that common = a does not copy anything. It is a second reference to the same set, so retainAll removed apple from a itself. Any later code that uses a now works on wrong data. If a had been created with Set.of, the call would instead have thrown UnsupportedOperationException, because Set.of returns an unmodifiable set. Either way, the caller who passed us a and b did not expect us to touch them.

3The Fix: Copy First, Then Apply the Operation

The correct pattern is to create a new set from a, which copies its elements, and then apply the bulk method to the copy. The originals stay untouched.

Java
Set<String> a = Set.of("apple", "banana", "cherry");
Set<String> b = Set.of("banana", "cherry", "date");
Set<String> union = new HashSet<>(a);
union.addAll(b); // [apple, banana, cherry, date] (order may vary)
Set<String> intersection = new HashSet<>(a);
intersection.retainAll(b); // [banana, cherry]
Set<String> difference = new HashSet<>(a);
difference.removeAll(b); // [apple]
System.out.println(a); // [apple, banana, cherry] unchanged
System.out.println(b); // [banana, cherry, date] unchanged
The three operations on a = {apple, banana, cherry}, b = {banana, cherry, date}
OperationCode on a copy of aResult
Unioncopy.addAll(b)apple, banana, cherry, date
Intersectioncopy.retainAll(b)banana, cherry
Difference a - bcopy.removeAll(b)apple
Difference b - acopy of b, then removeAll(a)date

Each operation gets its own copy, so the three results do not interfere with each other either. The copy costs time and memory proportional to the size of a, which is the price of not mutating the inputs. If we need a predictable order in the result, for example for logging or a test, we copy into a LinkedHashSet, which keeps a's order, or a TreeSet, which sorts the elements.

The same results can be written with streams, which some teams find more readable, though it is not faster.

4The Same Operations With Streams

Streams make the result a new set by construction, so there is no receiver to mutate.

Java
Set<String> union = Stream.concat(a.stream(), b.stream())
.collect(Collectors.toSet()); // [apple, banana, cherry, date]
Set<String> intersection = a.stream().filter(b::contains)
.collect(Collectors.toSet()); // [banana, cherry]
Set<String> difference = a.stream().filter(e -> !b.contains(e))
.collect(Collectors.toSet()); // [apple]

Notice that b::contains is called once per element of a. That is fast when b is a HashSet, where contains is O(1) on average, and slow if b is a List, where contains scans the whole list. The same point decides how fast retainAll and removeAll are, which brings us to large sets.

5Making the Intersection Fast for Large Sets

Inside the JDK, retainAll on a HashSet walks through every element of the receiver and calls b.contains for each one, removing the ones b does not have. So intersection.retainAll(b) costs one lookup per element of a, plus the cost of copying a first. If a has 5,000,000 elements and b has 1,000, we copy five million elements and do five million lookups, only to keep at most a thousand.

Since the intersection can never be larger than the smaller set, we iterate the smaller one and look up each element in the larger one.

Java
static <T> Set<T> intersect(Set<T> a, Set<T> b) {
Set<T> small = a.size() <= b.size() ? a : b;
Set<T> large = small == a ? b : a;
Set<T> result = new HashSet<>();
for (T e : small) {
if (large.contains(e)) result.add(e);
}
return result;
}
// a has 5,000,000 elements, b has 1,000
intersect(a, b); // 1,000 lookups instead of copying and checking 5,000,000

This only works because large.contains is fast, so the larger set should be a HashSet or another hash-based set. If one input is a List, we convert it to a HashSet first, otherwise every contains call becomes a scan. The union does not benefit from the same trick, since every element of both sets ends up in the result, but we can at least copy the larger set and add the smaller one to it, so the hash table is sized well from the start.

6Follow-up questions

How would you compute the symmetric difference, the elements in exactly one of the sets?

Compute the union and the intersection on copies, then remove the intersection from the union: copy a into u and call u.addAll(b), copy a into i and call i.retainAll(b), then u.removeAll(i). For a and b above that gives apple and date. Another way is to add (a minus b) and (b minus a) into one result set.

Does retainAll work if b is a List?

Yes, it gives the right answer, because it only calls b.contains. But each contains call on an ArrayList scans the list, so the total cost becomes the size of a times the size of b. For large inputs we convert b to a HashSet first, which costs one pass over b and makes every lookup constant time on average.

How do you return the result so the caller cannot change it?

Wrap or copy it at the end: Set.copyOf(result) returns an unmodifiable copy, and Collections.unmodifiableSet(result) returns a read-only view. Set.copyOf also rejects null elements, so if the input sets might contain null we use the view instead.

7Conclusion

In this answer, we computed union, intersection and difference by copying a into a new set and calling addAll, retainAll or removeAll on the copy, because those methods mutate their receiver and calling them on a directly corrupts or rejects the caller's data. We saw the same operations with streams, learned that their speed depends on contains being fast on the other set, and made large intersections cheap by iterating the smaller set and looking elements up in the larger one.

What to say in the interviewAbout 90 seconds aloud

Open with

The bulk methods on Set do what we need, but they mutate the set they are called on, so the important part is to copy first. For the union I write new HashSet of a, then addAll of b.

Then, if they want more

For the intersection, a new HashSet of a, then retainAll of b. For a minus b, a new HashSet of a, then removeAll of b. Each operation gets its own copy, so a and b stay unchanged and the results do not affect each other.

If I called retainAll on a directly, I would silently remove elements from the caller's set, or get an UnsupportedOperationException if a came from Set.of. If the order of the result matters, I copy into a LinkedHashSet or a TreeSet instead.

For large sets, I think about what the methods do internally: retainAll walks the receiver and calls contains on the argument, so its cost is the size of the receiver times the cost of contains.

For an intersection I iterate the smaller set and check contains on the larger one, because the result can never be bigger than the smaller set, and I make sure the larger one is a HashSet, converting a List first if needed, since contains on a List is a linear scan.

Finally, if the caller should not modify the result, I return Set.copyOf of it.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Given two Set<String> a and b, write code to compute their union, intersection and...": https://scrivio-interview-library.netlify.app/java/sets/21de00c024/