Sets: interview questions & scenarios
These are the set questions I ask when I want to know whether you understand uniqueness, ordering and mutation rather than only collection names. The trick is that the same word, duplicate, means equals in one set and comparison result 0 in another.
Here's how to use this page: read the question, say your answer out loud first, then open the model answer. The follow-ups point back to the lessons: How HashSet, LinkedHashSet and TreeSet work and Set operations: union, intersection and difference.
You receive product names from a CSV and need to store each unique product once. Which set do you choose, and what do you do about case and spaces?
Tests HashSet, normalization, insertion order
Show answerHide answer
Model answer
Use a HashSet for the membership part, but normalize the value before putting it in the set. If the business rule says " Mouse ", "mouse" and "MOUSE" are the same product name, trim the text and apply a locale-stable case rule, usually toLowerCase(Locale.ROOT).
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
public class ProductNameDedup {
public static void main(String[] args) {
List<String> rows = List.of(" Mouse ", "mouse", "Keyboard");
Set<String> names = new HashSet<>();
for (String raw : rows) {
String normalized = raw.trim().toLowerCase(Locale.ROOT);
if (!normalized.isEmpty()) {
names.add(normalized);
}
}
System.out.println(names);
}
}
If the UI must show products in the order they first appeared in the file, switch the concrete type to LinkedHashSet. You still get expected O(1) membership, but iteration is first-seen order. Do not rely on HashSet iteration order, even if it looks stable in a small test.
How I’d say it in the interview
"I'd use a HashSet after defining what duplicate means. For names, I would normalize case and whitespace first, then add the normalized key. If the output needs first-seen display order, I'd use LinkedHashSet instead of HashSet."
Signals depth
Calling out the normalization step before insertion, using Locale.ROOT for case conversion, and separating membership order from display order.
Red flags
"HashSet removes duplicates automatically" without asking whether "Mouse" and " mouse " should match. Also, depending on the current HashSet print order.
Follow-ups interviewers ask next
What if the UI must display the original spelling from the first row?
Keep a
LinkedHashMap<String, String>from normalized name to first raw display name. The key handles uniqueness; the value preserves what you want to show.What if names are user-visible in Turkish or another locale-sensitive language?
Do not invent the equality rule inside the collection. Agree on a product identity rule with the domain team. For internal identifiers,
Locale.ROOTis usually right; for human sorting and searching, use a proper collator or search system.
You need unique student IDs in ascending order. Which collection would you use?
Tests TreeSet, natural ordering, navigation
Show answerHide answer
Model answer
Use a TreeSet if the collection must stay unique and sorted as you add IDs. It is backed by a tree, so add, remove and contains are O(log n), and iteration is ascending according to natural order or the comparator you pass.
import java.util.NavigableSet;
import java.util.TreeSet;
public class SortedStudentIdsExample {
public static void main(String[] args) {
NavigableSet<Integer> ids = new TreeSet<>();
ids.add(1042);
ids.add(1007);
ids.add(1042);
ids.add(1099);
System.out.println(ids); // [1007, 1042, 1099]
System.out.println(ids.ceiling(1050)); // 1099
}
}
If you only sort once at the end, a HashSet plus a final sort can be cheaper. But when the invariant is "always unique and ordered", TreeSet states that invariant directly.
How I’d say it in the interview
"TreeSet. It gives me uniqueness plus sorted iteration all the time, and it also gives navigation methods like floor and ceiling. I would only use HashSet plus sorting if sorted order is a final reporting step."
Signals depth
Mentioning the O(log n) update cost and the fact that TreeSet uniqueness is based on comparison, not equals.
Red flags
Choosing ArrayList and saying you will "check duplicates manually" without a reason.
Follow-ups interviewers ask next
What if IDs arrive as strings like
"S-2"and"S-10"?Natural string order puts
"S-10"before"S-2". Use a comparator that parses the numeric part, and add a tie-breaker if two different IDs could parse to the same number.
Your system has fixed user roles: ADMIN, USER, GUEST and AUDITOR. Which set type should represent a user's roles?
Tests EnumSet, fixed constants, bit operations
Model answer, how to say it, 1 follow-up: unlock with the Java Pass
You need to keep users in sign-up order, but no duplicate user IDs are allowed. What should you store?
Tests LinkedHashSet, LinkedHashMap, object identity
Model answer, how to say it, 2 follow-ups: unlock with the Java Pass
How does HashSet.add(e) work internally?
Tests HashMap backing, equals, hashCode
Model answer, how to say it, 1 follow-up: unlock with the Java Pass
This set has size 1, but contains returns false. Debug it.
Tests mutable elements, hash buckets, remove before mutate
Model answer, how to say it, 1 follow-up: unlock with the Java Pass
What does this print, and why?
Tests TreeSet, comparator inconsistent with equals
Model answer, how to say it, 2 follow-ups: unlock with the Java Pass
Write union, intersection and difference without mutating either input.
Tests copy-first set algebra, generics, mutating methods
Model answer, how to say it, 1 follow-up: unlock with the Java Pass
A cleanup job calls ids.removeAll(blockedList) and gets much slower as blockedList grows. Why?
Tests AbstractSet.removeAll, contains cost, asymptotic traps
Model answer, how to say it, 1 follow-up: unlock with the Java Pass
Premium question set
Keep reading with the Java Pass
The rest of this question set is part of Java One-Stop Interview Prep: in-depth explanations, diagrams, model answers and how to say them in the interview.
From ₹199 · one-time payment · No auto-renewal