Java
Arrays
Intersection
Coding
Algorithm

Java, find intersection of two arrays

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Finding the intersection of two arrays sounds simple until you need to decide what "intersection" actually means. Some use cases want unique values only, while others want duplicates preserved based on frequency. In Java, the right implementation depends on that rule, plus whether you care more about simplicity, order, or time complexity.

Define the Intersection Rule First

Before writing code, choose one of these interpretations:

  • Unique intersection: each common value appears once in the result.
  • Multiset intersection: duplicates are preserved up to the minimum count in both arrays.

For arrays 1, 2, 2, 3 and 2, 2, 4, the unique intersection is 2, while the multiset intersection is 2, 2.

That distinction changes the data structure you should use.

Unique Intersection With HashSet

If you only need unique values, use a set for fast membership checks. This keeps the code short and runs in linear time on average.

java
1import java.util.Arrays;
2import java.util.HashSet;
3import java.util.Set;
4
5public class UniqueIntersection {
6    public static int[] intersect(int[] a, int[] b) {
7        Set<Integer> left = new HashSet<>();
8        Set<Integer> result = new HashSet<>();
9
10        for (int value : a) {
11            left.add(value);
12        }
13
14        for (int value : b) {
15            if (left.contains(value)) {
16                result.add(value);
17            }
18        }
19
20        return result.stream().mapToInt(Integer::intValue).toArray();
21    }
22
23    public static void main(String[] args) {
24        int[] output = intersect(new int[] {1, 2, 2, 3}, new int[] {2, 2, 4});
25        System.out.println(Arrays.toString(output));
26    }
27}

This is the best baseline for most interview-style or data-cleaning cases where duplicates are irrelevant.

Preserving Duplicates With a Frequency Map

If duplicates matter, a set is not enough because it loses counts. Use a frequency map for one array, then consume matches from the other.

java
1import java.util.ArrayList;
2import java.util.Arrays;
3import java.util.HashMap;
4import java.util.List;
5import java.util.Map;
6
7public class MultisetIntersection {
8    public static int[] intersect(int[] a, int[] b) {
9        Map<Integer, Integer> counts = new HashMap<>();
10        List<Integer> result = new ArrayList<>();
11
12        for (int value : a) {
13            counts.put(value, counts.getOrDefault(value, 0) + 1);
14        }
15
16        for (int value : b) {
17            int remaining = counts.getOrDefault(value, 0);
18            if (remaining > 0) {
19                result.add(value);
20                counts.put(value, remaining - 1);
21            }
22        }
23
24        return result.stream().mapToInt(Integer::intValue).toArray();
25    }
26
27    public static void main(String[] args) {
28        int[] output = intersect(new int[] {1, 2, 2, 3}, new int[] {2, 2, 4});
29        System.out.println(Arrays.toString(output));
30    }
31}

This returns 2, 2, which is correct for multiset logic.

Sorting as an Alternative

If the arrays are already sorted, or if sorting cost is acceptable, you can use a two-pointer scan. This avoids hashing and can be memory efficient.

java
1import java.util.ArrayList;
2import java.util.Arrays;
3import java.util.List;
4
5public class SortedIntersection {
6    public static int[] intersect(int[] a, int[] b) {
7        Arrays.sort(a);
8        Arrays.sort(b);
9
10        int i = 0;
11        int j = 0;
12        List<Integer> result = new ArrayList<>();
13
14        while (i < a.length && j < b.length) {
15            if (a[i] == b[j]) {
16                result.add(a[i]);
17                i++;
18                j++;
19            } else if (a[i] < b[j]) {
20                i++;
21            } else {
22                j++;
23            }
24        }
25
26        return result.stream().mapToInt(Integer::intValue).toArray();
27    }
28}

This pattern naturally preserves duplicate matches and is useful when you want deterministic numeric ordering in the output.

Which Approach Should You Choose

Use HashSet when:

  • You only care about unique common values.
  • Output order does not matter.
  • You want the simplest linear solution.

Use a frequency map when:

  • Duplicate counts matter.
  • You want linear behavior without sorting both arrays.

Use sorting and two pointers when:

  • Arrays are already sorted or easy to sort.
  • You want to minimize extra map overhead.
  • Ordered output is useful.

Common Pitfalls

  • Writing an intersection method without defining whether duplicates should be preserved.
  • Using List.contains inside a loop, which turns the solution into quadratic time for large inputs.
  • Forgetting that HashSet does not preserve insertion order.
  • Sorting the input arrays in place when callers expect the original order to remain unchanged.
  • Returning boxed Integer collections when the rest of the code expects primitive int[].

Summary

  • Decide first whether you want unique or multiset intersection semantics.
  • 'HashSet is the simplest solution for unique results.'
  • A frequency map is the correct choice when duplicates matter.
  • Sorting plus two pointers is a good option for ordered or already sorted data.
  • The main bug source is ambiguity in requirements, not Java syntax.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.