← Back to libraryQuestion 91 of 273
⌨️Java CodingIntermediate

Find the Intersection of Two Arrays

📌 Definition:

Return the common elements of two arrays (e.g. [1,2,2,3] and [2,3,4] -> [2,3] for the distinct version).

📖 Detailed Explanation:

Put one array’s elements in a hash set, then scan the other and collect elements present in the set (moving matches into a result set to avoid repeats). O(n + m). Sorting both and using two pointers is the O(1)-extra-space alternative.

💻 Solutions:
public static Set<Integer> intersection(int[] a, int[] b) {
    Set<Integer> set = new HashSet<>();
    for (int x : a) set.add(x);
    Set<Integer> out = new LinkedHashSet<>();
    for (int x : b) if (set.contains(x)) out.add(x);
    return out;
}
function intersection(a, b) {
  const set = new Set(a);
  return [...new Set(b.filter(x => set.has(x)))];
}
def intersection(a, b):
    return list(set(a) & set(b))
🔑 Key Points:
  • Hash set of one array, probe with the other
  • Collect matches in a set to dedupe
  • O(n + m) time
  • Two-pointer on sorted inputs is the low-space option
🌍 Real-World Example:

Set intersection answers "which records exist in both systems?" — a routine reconciliation across two data sources.

🎯 Scenario-Based Interview Question:

Should duplicates in the inputs appear multiple times in the result?